#!/bin/bash
# 智子频道 frpc 一键安装脚本
# 用法：
#   bash install-frpc.sh                      # 仅下载并安装 frpc 二进制（需自备 frpc.toml）
#   bash install-frpc.sh /path/frpc.toml      # 安装并注册为系统服务（开机自启）
set -e
CFG="$1"
VER="0.72.0"
BASE="https://zz.iotzz.cn/downloads"
GH="https://github.com/fatedier/frp/releases/download/v${VER}"

OS=$(uname -s); ARCH=$(uname -m)
if [ "$OS" = "Darwin" ]; then
  PKG="frpc-darwin-amd64"
elif [ "$ARCH" = "x86_64" ] || [ "$ARCH" = "amd64" ]; then
  PKG="frpc-linux-amd64"
elif [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then
  PKG="frpc-linux-arm64"
elif [ "$ARCH" = "armv7l" ] || [ "$ARCH" = "armhf" ]; then
  PKG="frpc-linux-arm"
else
  echo "不支持的架构: $OS/$ARCH"; exit 1
fi

echo "== 下载 frpc 客户端 ($PKG) =="
if ! curl -fsSL --connect-timeout 10 --max-time 120 "$BASE/$PKG" -o /usr/local/bin/frpc; then
  echo "站点下载失败，回退到 GitHub 镜像..."
  DIR="frp_${VER}_${PKG#frpc-}"
  ok=0
  for m in "https://ghproxy.net/$GH" "https://gh-proxy.com/$GH" "https://ghfast.top/$GH" "$GH"; do
    if curl -fsSL --connect-timeout 10 --max-time 180 "$m/$DIR.tar.gz" -o /tmp/frp_pkg.tgz; then
      rm -rf "/tmp/$DIR"; tar -xzf /tmp/frp_pkg.tgz -C /tmp
      SRC="/tmp/$DIR/frpc"; [ -f /tmp/$DIR/frpc.exe ] && SRC="/tmp/$DIR/frpc.exe"
      cp "$SRC" /usr/local/bin/frpc; ok=1; break
    fi
  done
  [ "$ok" = "1" ] || { echo "所有下载源均失败，请手动下载 frpc"; exit 1; }
fi
chmod +x /usr/local/bin/frpc
echo "frpc 已安装: $(frpc --version 2>/dev/null || echo ok)"

if [ -n "$CFG" ]; then
  if [ ! -f "$CFG" ]; then echo "配置文件不存在: $CFG"; exit 1; fi
  if [ "$OS" = "Darwin" ]; then
    nohup /usr/local/bin/frpc -c "$CFG" >/tmp/frpc.log 2>&1 &
    echo "macOS: frpc 已后台启动，日志 /tmp/frpc.log"
    exit 0
  fi
  cat > /etc/systemd/system/frpc.service <<UNIT
[Unit]
Description=frpc tunnel client
After=network.target
[Service]
ExecStart=/usr/local/bin/frpc -c $CFG
Restart=on-failure
[Install]
WantedBy=multi-user.target
UNIT
  systemctl daemon-reload
  systemctl enable --now frpc
  echo "frpc 服务已启动，状态："
  systemctl status frpc --no-pager || true
fi
