#!/bin/bash
# install_tailscale.sh — 在服务器上安装 Tailscale（官方 apt 源，Ubuntu/Debian）
# 不用 curl|sh：只拉官方 GPG key + apt 源清单这两个数据文件，包本体走 apt 校验安装
set -e
. /etc/os-release
SUITE="${VERSION_CODENAME}"
echo "系统: ${PRETTY_NAME}   codename=${SUITE}"
if ! command -v tailscale >/dev/null 2>&1; then
  echo "[1/3] 添加官方 key + apt 源..."
  curl -fsSL "https://pkgs.tailscale.com/stable/ubuntu/${SUITE}.noarmor.gpg" -o /usr/share/keyrings/tailscale-archive-keyring.gpg
  curl -fsSL "https://pkgs.tailscale.com/stable/ubuntu/${SUITE}.tailscale-keyring.list" -o /etc/apt/sources.list.d/tailscale.list
  echo "  key 指纹: $(gpg --show-keys --with-fingerprint /usr/share/keyrings/tailscale-archive-keyring.gpg 2>/dev/null | grep -m1 -A1 pub | tail -1 || md5sum /usr/share/keyrings/tailscale-archive-keyring.gpg | cut -c1-16)"
  echo "  源清单: $(cat /etc/apt/sources.list.d/tailscale.list)"
  echo "[2/3] apt update + install..."
  apt-get update -qq
  DEBIAN_FRONTEND=noninteractive apt-get install -y -qq tailscale
else
  echo "[1/2] 已安装，跳过"
fi
echo "[3/3] 版本: $(tailscale version | head -1)"
echo "--- 启动 tailscaled ---"
systemctl enable --now tailscaled >/dev/null 2>&1 || tailscaled --tun=userspace-networking --socks5-server=localhost:1055 --outbound-http-proxy-listen=localhost:1055 >/tmp/tailscaled.log 2>&1 &
sleep 3
systemctl is-active tailscaled 2>/dev/null || echo "(tailscaled 可能以后台进程运行)"
echo "--- 拉起 tailscale up（会打印授权 URL）---"
nohup tailscale up --hostname=hw-crawler --accept-dns=false > /tmp/ts_up.log 2>&1 &
sleep 12
echo "===== 授权 URL ====="
grep -oE "https://login\.tailscale\.com/[a-z]/[a-z0-9]+" /tmp/ts_up.log | head -1
echo "===== 原始输出 ====="
cat /tmp/ts_up.log | head -12
