#!/bin/bash
set -e

# 颜色控制
RED='\033[0;31m'
NC='\033[0m' # No Color

usage() {
    echo "用法: $0 --domain 域名[,域名2] [--disable-ipv6]"
    echo "示例: $0 --domain example.com,sub.example.com --disable-ipv6"
    exit 1
}

DISABLE_IPV6=false
DOMAINS_INPUT=""
while [[ $# -gt 0 ]]; do
    case "$1" in
        --domain|-d)
            if [[ -z "${2:-}" ]]; then
                echo -e "${RED}--domain 需要一个域名参数。${NC}"
                usage
            fi
            DOMAINS_INPUT="$2"
            shift 2
            ;;
        --disable-ipv6)
            DISABLE_IPV6=true
            shift
            ;;
        -h|--help)
            usage
            ;;
        *)
            echo -e "${RED}未知参数: $1${NC}"
            usage
            ;;
    esac
done

if [[ -z "$DOMAINS_INPUT" ]]; then
    echo -e "${RED}必须通过 --domain 指定域名。${NC}"
    usage
fi

IFS=',' read -ra CHECK_DOMAINS <<< "$DOMAINS_INPUT"
for domain in "${CHECK_DOMAINS[@]}"; do
    domain=$(echo "$domain" | xargs)
    if [[ -z "$domain" || ! $domain =~ ^([a-zA-Z0-9](([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)\.)+[a-zA-Z]{2,}$ ]]; then
        echo -e "${RED}域名格式不正确: ${domain:-<空>} (示例: example.com)${NC}"
        exit 1
    fi
done

# --- 关闭 IPv6 ---
if [ "$DISABLE_IPV6" = true ]; then
echo "正在关闭 IPv6..."

SYSCTL_CONF="/etc/sysctl.conf"
sysctl_ok=true
touch "$SYSCTL_CONF" || sysctl_ok=false
if [ -n "$(tail -c 1 "$SYSCTL_CONF" 2>/dev/null || true)" ]; then
    echo >> "$SYSCTL_CONF" || sysctl_ok=false
fi

while IFS= read -r line; do
    if ! grep -qxF "$line" "$SYSCTL_CONF" 2>/dev/null; then
        echo "$line" >> "$SYSCTL_CONF" || sysctl_ok=false
    fi
done <<'EOF'
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
EOF

if ! sysctl -p; then
    sysctl_ok=false
fi

if [ "$sysctl_ok" = true ]; then
    echo "sysctl 已关闭 IPv6。"
else
    echo -e "${RED}sysctl 关闭 IPv6 失败，继续执行后续步骤。${NC}"
fi

GRUB_FILE="/etc/default/grub"
grub_ok=true
if [ ! -f "$GRUB_FILE" ]; then
    echo -e "${RED}未找到 ${GRUB_FILE}，无法写入 ipv6.disable=1。${NC}"
    grub_ok=false
else
    if ! grep -q '^GRUB_CMDLINE_LINUX_DEFAULT="[^"]*ipv6.disable=1' "$GRUB_FILE"; then
        if grep -q '^GRUB_CMDLINE_LINUX_DEFAULT="' "$GRUB_FILE"; then
            sed -i 's/^GRUB_CMDLINE_LINUX_DEFAULT="\(.*\)"/GRUB_CMDLINE_LINUX_DEFAULT="\1 ipv6.disable=1"/' "$GRUB_FILE" || grub_ok=false
            sed -i 's/^GRUB_CMDLINE_LINUX_DEFAULT=" ipv6.disable=1"/GRUB_CMDLINE_LINUX_DEFAULT="ipv6.disable=1"/' "$GRUB_FILE" || grub_ok=false
        else
            echo 'GRUB_CMDLINE_LINUX_DEFAULT="ipv6.disable=1"' >> "$GRUB_FILE" || grub_ok=false
        fi
    fi

    if [ "$grub_ok" = true ] && ! grep -q '^GRUB_CMDLINE_LINUX_DEFAULT="[^"]*ipv6.disable=1' "$GRUB_FILE"; then
        echo -e "${RED}未能把 ipv6.disable=1 写入 GRUB_CMDLINE_LINUX_DEFAULT。${NC}"
        grub_ok=false
    fi

    if [ "$grub_ok" = true ]; then
        if ! command -v update-grub >/dev/null 2>&1; then
            echo -e "${RED}未找到 update-grub。${NC}"
            grub_ok=false
        elif ! update-grub; then
            grub_ok=false
        fi
    fi
fi

if [ "$grub_ok" = true ]; then
    echo "GRUB 已写入 ipv6.disable=1。重启后内核参数才会生效。"
else
    echo -e "${RED}GRUB 关闭 IPv6 失败，继续执行后续步骤。${NC}"
fi
else
    echo "已跳过关闭 IPv6。"
fi

# 检查 Docker 环境
if ! command -v docker &> /dev/null; then
    echo "未检测到 Docker 环境，正在安装..."
    curl -sSL https://get.docker.com/ | sh
    systemctl enable --now docker
    echo "Docker 安装完成。"
fi

# 默认值
DEFAULT_MTG_SECRET="a84d803627f69d69a843150d0ead8cc7"
SINGBOX_UUID="8f4b3a5b-47a5-45c6-957a-b3a5c678f9c1"
SINGBOX_PORT_START=10808
MTG_PORT=31288
MTG_CMD_VAR="$DEFAULT_MTG_SECRET"

# 解析域名并去除空格；Caddy 与 Singbox 共用同一组域名
IFS=',' read -ra DOMAINS <<< "$DOMAINS_INPUT"
DOMAINS=("${DOMAINS[@]// /}")

echo "正在生成配置文件..."

# --- 创建目录 ---
mkdir -p caddy/data caddy/config
echo "已创建 caddy 相关目录。"


# --- 生成 Caddyfile ---
cat > Caddyfile <<EOF
{
    email airplayx@gmail.com
    log {
        level ERROR
    }
}

:80 {
    root * /usr/share/caddy
    file_server
}
EOF

for domain in "${DOMAINS[@]}"; do
    cat >> Caddyfile <<EOF

$domain {
    encode gzip zstd
    log {
        level ERROR
    }

    @options {
        method OPTIONS
    }
    respond @options 204

    @blockUA {
        header_regexp User-Agent "(?i)baiduspider|360spider|Sogou web spider|Sosospider|YisouSpider|Bingbot|Googlebot|Scrapy|Curl|HttpClient|python-requests|Go-http-client|WinHttp|WebZIP|FetchURL|node-superagent|java/|FeedDemon|Jullo|JikeSpider|Indy Library|Alexa Toolbar|AskTbFXTV|AhrefsBot|CrawlDaddy|Java|Feedly|Apache-HttpAsyncClient|UniversalFeedParser|ApacheBench|Microsoft URL Control|Swiftbot|ZmEu|oBot|jaunty|Python-urllib|lightDeckReports Bot|YYSpider|DigExt|MJ12bot|heritrix|EasouSpider|Ezooms|BOT/0.1|YandexBot|FlightDeckReports|SemrushBot|Linguee Bot"
    }
    respond @blockUA 403
}
EOF
done
echo "Caddyfile 已生成。"

# --- 生成 singbox.json ---
export SINGBOX_PORT_START SINGBOX_UUID
export DOMAINS_JSON=$(printf '%s\n' "${DOMAINS[@]}" | python3 -c 'import sys, json; print(json.dumps([line.strip() for line in sys.stdin if line.strip()]))')

python3 -c '
import json, os

domains = json.loads(os.environ["DOMAINS_JSON"])
start_port = int(os.environ["SINGBOX_PORT_START"])

inbounds = []
for i, domain in enumerate(domains):
    inbounds.append({
        "type": "vless",
        "tag": f"vless-in-{i+1}",
        "listen": "::",
        "listen_port": start_port + i,
        "users": [
            {
                "uuid": os.environ["SINGBOX_UUID"]
            }
        ],
        "tls": {
            "enabled": True,
            "server_name": domain,
            "key_path": f"/etc/sing-box/ssl/{domain}/{domain}.key",
            "certificate_path": f"/etc/sing-box/ssl/{domain}/{domain}.crt",
            "alpn": [
                "h2", 
                "http/1.1"
            ]
        },
        "transport": {
            "type": "http",
            "host": domain,
            "path": "/"
        }
    })

config = {
    "log": {
        "level": "error"
    },
    "inbounds": inbounds,
    "outbounds": [
        {
            "type": "direct"
        }
    ]
}
print(json.dumps(config, indent=2))
' > singbox.json
echo "singbox.json 已生成。"

# --- 生成 docker-compose.yml ---
SB_VOLUMES=""
SB_PORTS=""

i=0
for domain in "${DOMAINS[@]}"; do
    domain=$(echo "$domain" | xargs)
    SB_VOLUMES+="      - ./caddy/data/caddy/certificates/acme-v02.api.letsencrypt.org-directory/$domain/:/etc/sing-box/ssl/$domain/\n"
    SB_VOLUMES+="      - ./caddy/data/caddy/certificates/acme.zerossl.com-v2-dv90/$domain/:/etc/sing-box/ssl/${domain}_zs/\n"
    
    current_sb_port=$((SINGBOX_PORT_START + i))
    SB_PORTS+="      - \"$current_sb_port:$current_sb_port\"\n"
    i=$((i+1))
done

cat > docker-compose.yml <<EOF
services:
  mtg:
    image: p3terx/mtg
    container_name: mtg
    privileged: true
    restart: unless-stopped
    command: ["run", "$MTG_CMD_VAR"]
    ports:
      - "${MTG_PORT}:3128"

  caddy:
    image: zanpiancms/caddy
    container_name: caddy
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    environment:
      ACME_AGREE: true
      TZ: Asia/Shanghai
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile
      - ./caddy/data:/data
      - ./caddy/config:/config      
    networks:
      - app-network
    healthcheck:
      test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:80"]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 10s

  singbox:
    image: ghcr.io/sagernet/sing-box
    container_name: singbox
    restart: unless-stopped
    depends_on:
      caddy:
        condition: service_healthy
    volumes:
$(printf "$SB_VOLUMES")
      - ./singbox.json:/etc/sing-box/config.json:ro
    command: -D /var/lib/sing-box -C /etc/sing-box/ run
    ports:
$(printf "$SB_PORTS")

  speedtestx:
    image: badapple9/speedtest-x
    container_name: speedtestx
    restart: unless-stopped
    ports:
      - "9001:80"

networks:
  app-network:
    driver: bridge
EOF
echo "docker-compose.yml 已生成。"

# --- 智能启动与回滚逻辑 ---
# 1. 启动 Caddy
echo "正在启动 Caddy 并申请证书..."
docker compose up -d caddy

# 2. 等待证书锁
echo "正在等待证书文件生成 (最长等待 150 秒)..."
FIRST_DOMAIN=$(echo "${DOMAINS[0]}" | xargs)
COUNTER=0
MAX_RETRIES=30 

while [ $COUNTER -lt $MAX_RETRIES ]; do
    # 只要在 data 目录下能找到对应域名后缀的 .crt 文件即可（兼容 LE 和 ZeroSSL 目录名）
    if find ./caddy/data -name "*${FIRST_DOMAIN}.crt" | grep -q "${FIRST_DOMAIN}"; then
        echo -e "\n检测到证书已就绪！"
        break
    fi
    printf "."
    sleep 5
    COUNTER=$((COUNTER + 1))
done

if [ $COUNTER -eq $MAX_RETRIES ]; then
    echo -e "\n${RED}警告：证书申请超时。如果后续启动失败，可能是由于证书尚未下发。${NC}"
fi

# 3. 启动其余服务
echo "正在启动 MTG、Singbox 和 SpeedtestX..."
if ! docker compose up -d; then
    echo -e "${RED}错误: 启动失败，执行自动回滚...${NC}"
    docker compose down 2>/dev/null || true
    rm -rf caddy/ Caddyfile singbox.json docker-compose.yml
    exit 1
fi

echo "部署成功！所有服务已进入运行状态。"
echo ""
echo "========== 连接信息 =========="

echo ""
echo "Singbox:"
i=0
for domain in "${DOMAINS[@]}"; do
    domain=$(echo "$domain" | xargs)
    port=$((SINGBOX_PORT_START + i))
    echo "vless://${SINGBOX_UUID}@${domain}:${port}?host=${domain}&path=%2F&mode=stream-one&type=xhttp&encryption=none&security=tls&alpn=h2%2Chttp%2F1.1&sni=${domain}#${domain}"
    i=$((i+1))
done

echo ""
echo "正在获取当前服务器公网 IP..."
SERVER_IP=""
for url in "https://ifconfig.me" "https://ip.sb" "https://icanhazip.com" "https://api.ipify.org"; do
    SERVER_IP=$(curl -fsS4 --max-time 5 "$url" 2>/dev/null | tr -d '[:space:]')
    if [[ $SERVER_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        break
    fi
    SERVER_IP=""
done

if [[ -z "$SERVER_IP" ]]; then
    echo -e "${RED}无法自动获取服务器公网 IP，请手动输入。${NC}"
    read -p "请输入服务器公网 IP: " SERVER_IP
    SERVER_IP=$(echo "$SERVER_IP" | xargs)
fi

if [[ ! $SERVER_IP =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    SERVER_IP=$(echo "${DOMAINS[0]}" | xargs)
    echo -e "${RED}未获得有效公网 IP，MTG 链接改用域名: $SERVER_IP${NC}"
fi

MTG_SECRET_B64=$(printf '%s' "$MTG_CMD_VAR" | python3 -c '
import sys, binascii, base64
s = sys.stdin.read().strip()
hexdigits = set("0123456789abcdefABCDEF")
if len(s) % 2 == 0 and s and all(c in hexdigits for c in s):
    raw = binascii.unhexlify(s)
else:
    pad = "=" * ((4 - len(s) % 4) % 4)
    raw = base64.urlsafe_b64decode(s + pad)
print(base64.urlsafe_b64encode(raw).decode().rstrip("="))
')

echo ""
echo "MTG:"
echo "tg://proxy?server=${SERVER_IP}&port=${MTG_PORT}&secret=${MTG_SECRET_B64}"
echo "https://t.me/proxy?server=${SERVER_IP}&port=${MTG_PORT}&secret=${MTG_SECRET_B64}"

if [ "$DISABLE_IPV6" = true ]; then
    echo ""
    read -p "是否立即重启以使 ipv6.disable=1 生效？(y/N): " REBOOT_CONFIRM
    if [[ "$REBOOT_CONFIRM" =~ ^[Yy]$ ]]; then
        echo "正在重启..."
        reboot
    else
        echo "已跳过重启。需要时请手动执行 reboot。"
    fi
fi
