#!/bin/bash
# Project: Insight Sing-box Installer (Project Team)
# GitHub: akriamail | Version: V9-GitHub-Only-Proxy
# Description: English & Chinese bilingual comments included.

set -e

# --- 1. Cleanup Old Rules / 清理旧规则 ---
# Ensure no leftover TPROXY or TUN interference.
systemctl stop sing-box 2>/dev/null || true
ip route del default dev tun0 2>/dev/null || true
iptables -t mangle -F 2>/dev/null || true
while ip rule del fwmark 1 table 100 2>/dev/null; do :; done

# --- 2. Define Variables / 定义变量 ---
DOMAIN="insight.akria.net"
VERSION="1.12.17"
INSTALL_PATH="/usr/local/bin/sing-box"
CONFIG_FILE="/etc/sing-box/config.json"
NODE_INI_URL="http://$DOMAIN/nodes.ini"
ARCH=$(uname -m)
[ "$ARCH" = "aarch64" ] && FILE_ARCH="linux-arm64" || FILE_ARCH="linux-amd64"

# --- 3. Fetch IP & Download / 获取 IP 并下载 ---
# Resolve Server B IP via DNS to avoid loop.
SERVER_B_IP=$(dig @223.5.5.5 +short $DOMAIN | tail -n1)
FETCH_CMD="curl -fsSL --noproxy '*' --connect-timeout 5 --resolve $DOMAIN:80:$SERVER_B_IP"

echo "[1/3] Downloading binary ($FILE_ARCH)..."
$FETCH_CMD "http://$DOMAIN/sing-box-$VERSION-$FILE_ARCH.tar.gz" -o "/tmp/sing-box.tar.gz"
cd /tmp && tar -xzf sing-box.tar.gz
find . -name "sing-box" -type f -exec mv {} $INSTALL_PATH \;
chmod +x $INSTALL_PATH

# --- 4. Generate GitHub-Only Config / 生成 GitHub 专线配置 ---
echo "[2/3] Generating Dedicated Route Configuration..."
INI_DATA=$($FETCH_CMD "$NODE_INI_URL")

python3 -c "
import configparser, json, sys
try:
    config_ini = configparser.ConfigParser()
    config_ini.read_string(sys.argv[1])
    node = config_ini[config_ini.sections()[0]]
    config = {
        'log': {'level': 'info'},
        'inbounds': [
            {
                'type': 'tun',
                'tag': 'tun-in',
                'interface_name': 'tun0',
                'address': '172.19.0.1/30',
                'auto_route': True,
                'strict_route': False,
                'stack': 'gvisor',
                'sniff': True
            }
        ],
        'outbounds': [
            {
                'type': 'vmess', 'tag': 'proxy',
                'server': node.get('address'), 'server_port': int(node.get('port')),
                'uuid': node.get('uuid'), 'security': node.get('security', 'auto'),
                'network': node.get('network', 'tcp'),
                'tls': {'enabled': node.getboolean('tls', True), 'server_name': node.get('sni', node.get('address')), 'utls': {'enabled': True, 'fingerprint': 'chrome'}}
            },
            {'type': 'direct', 'tag': 'direct'}
        ],
        'route': {
            'rules': [
                {'port': [22], 'outbound': 'direct'},
                {'ip_is_private': True, 'outbound': 'direct'},
                {'domain_suffix': ['.cn', '.com.cn', '.gov.cn'], 'outbound': 'direct'},
                # Dedicated GitHub Routing / 仅代理 GitHub 相关流量
                {
                    'domain_keyword': ['github', 'raw.githubusercontent', 'gist.github', 'githubassets'],
                    'outbound': 'proxy'
                }
            ],
            'final': 'direct'
        }
    }
    with open('$CONFIG_FILE', 'w') as f:
        json.dump(config, f, indent=2)
except Exception as e:
    sys.exit(1)
" "$INI_DATA"

# --- 5. Service & Start / 服务注册与启动 ---
echo "[3/3] Starting Service (SSH Protected)..."
cat <<SEOF > /etc/systemd/system/sing-box.service
[Unit]
Description=sing-box service (Project Team)
After=network.target nss-lookup.target
[Service]
CapabilityBoundingSet=CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW
AmbientCapabilities=CAP_NET_ADMIN CAP_NET_BIND_SERVICE CAP_NET_RAW
ExecStart=$INSTALL_PATH run -c $CONFIG_FILE
Restart=on-failure
[Install]
WantedBy=multi-user.target
SEOF

systemctl daemon-reload
systemctl restart sing-box
echo "=== SUCCESS! GitHub-Only Acceleration is active. ==="
