#!/bin/bash

# --- 1. 环境准备 ---
# 检查是否为 root 用户
if [ "$EUID" -ne 0 ]; then 
  echo "请以 root 权限运行此脚本"
  exit 1
fi

# 提示用户选择系统类型
echo "请选择服务引导类型:"
echo "1) Systemd (Ubuntu, Debian, CentOS, etc.)"
echo "2) OpenWrt / iStoreOS (Procd)"
read -p "请输入选项 [1 or 2]: " TYPE

# --- 2. 源码下载与基础安装 ---
echo "正在克隆仓库并准备目录..."
# 如果目录已存在，先删除（可选）或跳过
rm -rf birdlgp 
git clone https://git.nia.ink/unet/birdlgp

mkdir -p /etc/bird-lg

# 移动程序和配置
if [ -f "birdlgp/bird-lgproxy-go" ]; then
    mv birdlgp/bird-lgproxy-go /etc/bird-lg/bird-lgproxy-go
    mv birdlgp/nexttrace /etc/bird-lg/nexttrace
    mv birdlgp/bird-lgproxy.yml /etc/bird-lg/bird-lgproxy.yml
else
    echo "错误：仓库中未找到 bird-lgproxy-go，请检查仓库内容。"
    exit 1
fi

# 赋予合理权限 (程序 755, 配置 644)
chmod 755 /etc/bird-lg/bird-lgproxy-go
chmod 755 /etc/bird-lg/nexttrace
chmod 644 /etc/bird-lg/bird-lgproxy.yml

# --- 3. 根据类型配置引导 ---
case $TYPE in
  1)
    echo "配置 Systemd 服务..."
    mv birdlgp/service/birdlgp.service /etc/systemd/system/birdlgp.service
    systemctl daemon-reload
    systemctl enable birdlgp.service
    systemctl start birdlgp.service
    ;;
    
  2)
    echo "配置 OpenWrt 服务..."
    mv birdlgp/service/bird-lgp-openwrt /etc/init.d/bird-lg-proxy
    chmod +x /etc/init.d/bird-lg-proxy
    /etc/init.d/bird-lg-proxy enable
    /etc/init.d/bird-lg-proxy start
    ;;
    
  *)
    echo "无效选项，脚本退出。"
    exit 1
    ;;
esac

# --- 4. 善后 ---
rm install.sh
rm -rf birdlgp 
echo "------------------------------------------------"
echo "Birdlgp 服务已成功安装并启动！"
echo "配置文件路径: /etc/bird-lg/config.yml"
echo "程序路径: /etc/bird-lg/bird-lgproxy-go"
echo "------------------------------------------------"