#!/bin/bash
# 服务器初始化和部署脚本 - Ubuntu 24.04
# 域名: tksea.top
# 服务器 IP: 43.155.133.187

set -e

echo "========================================"
echo "服务器初始化和部署脚本"
echo "========================================"

# 0. 检查是否是 root 用户
if [ "$EUID" -ne 0 ]; then
  echo "请使用 root 用户运行此脚本"
  exit 1
fi

# 1. 更新系统
echo "[1/14] 更新系统包..."
export DEBIAN_FRONTEND=noninteractive
apt update && apt upgrade -y

# 2. 安装基础工具
echo "[2/14] 安装基础工具..."
apt install -y curl wget vim git htop net-tools unzip certbot python3-certbot-nginx gnupg2 ca-certificates lsb-release

# 3. 安装 Docker
echo "[3/14] 安装 Docker..."
if ! command -v docker &> /dev/null; then
    install -m 0755 -d /etc/apt/keyrings
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
    chmod a+r /etc/apt/keyrings/docker.gpg
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null
    apt update
    apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
    systemctl enable docker
    systemctl start docker
fi

# 4. 验证 Docker
echo "[4/14] 验证 Docker 安装..."
docker --version
docker compose version

# 5. 安装 Nginx
echo "[5/14] 安装 Nginx..."
if ! command -v nginx &> /dev/null; then
    apt install -y nginx
fi

# 6. 配置防火墙
echo "[6/14] 配置防火墙..."
ufw allow 22/tcp
ufw allow 80/tcp
ufw allow 443/tcp
echo "y" | ufw enable 2>/dev/null || true

# 7. 创建应用目录
echo "[7/14] 创建应用目录..."
mkdir -p /opt/gitea
mkdir -p /opt/sub2api
mkdir -p /opt/nginx/ssl
mkdir -p /var/www/html

# 8. 配置 DNS 验证（用于 Let's Encrypt）
echo "[8/14] 配置 Nginx 用于 SSL..."
cat > /etc/nginx/sites-available/tksea.top << 'EOF'
server {
    listen 80;
    server_name tksea.top www.tksea.top;
    root /var/www/html;
    
    location / {
        return 200 "Sub2API Server";
    }
    
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }
}
EOF

ln -sf /etc/nginx/sites-available/tksea.top /etc/nginx/sites-enabled/
nginx -t
systemctl reload nginx

# 9. 获取 SSL 证书
echo "[9/14] 获取 SSL 证书..."
certbot --nginx -d tksea.top -d www.tksea.top --non-interactive --agree-tos --email admin@tksea.top --keep-until-expiring

# 10. 配置 Nginx 反向代理
echo "[10/14] 配置 Nginx 反向代理..."
cat > /etc/nginx/sites-available/tksea.top << 'EOF'
# HTTP 重定向到 HTTPS
server {
    listen 80;
    server_name tksea.top www.tksea.top;
    
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }
    
    location / {
        return 301 https://$server_name$request_uri;
    }
}

# HTTPS - Gitea (主域名)
server {
    listen 443 ssl http2;
    server_name tksea.top www.tksea.top;

    ssl_certificate /etc/letsencrypt/live/tksea.top/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/tksea.top/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    add_header Strict-Transport-Security "max-age=63072000" always;

    # Gitea 反向代理
    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

# sub2api 子域名
server {
    listen 443 ssl http2;
    server_name api.tksea.top;

    ssl_certificate /etc/letsencrypt/live/tksea.top/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/tksea.top/privkey.pem;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
    ssl_session_tickets off;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;
    
    add_header Strict-Transport-Security "max-age=63072000" always;
    
    underscores_in_headers on;

    # Sub2API 反向代理
    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
EOF

ln -sf /etc/nginx/sites-available/tksea.top /etc/nginx/sites-enabled/
nginx -t
systemctl reload nginx

# 11. 部署 Gitea
echo "[11/14] 部署 Gitea..."
cat > /opt/gitea/docker-compose.yml << 'EOF'
version: '3.8'

services:
  gitea:
    image: gitea/gitea:latest
    container_name: gitea
    restart: unless-stopped
    ports:
      - "127.0.0.1:3000:3000"
      - "127.0.0.1:2222:22"
    volumes:
      - gitea-data:/data
      - /etc/timezone:/etc/timezone:ro
      - /etc/localtime:/etc/localtime:ro
    environment:
      - USER_UID=1000
      - USER_GID=1000
      - GITEA__database__DB_TYPE=sqlite3
      - GITEA__server__DOMAIN=tksea.top
      - GITEA__server__ROOT_URL=https://tksea.top/
      - GITEA__server__HTTP_PORT=3000
      - GITEA__ssh__DOMAIN=tksea.top
      - GITEA__ssh__PORT=2222
      - GITEA__webhook__ALLOWED_HOSTS=tksea.top
    healthcheck:
      test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:3000/"]
      interval: 30s
      timeout: 10s
      retries: 3

volumes:
  gitea-data:
    name: gitea-data
EOF

cd /opt/gitea
docker compose up -d
echo "等待 Gitea 启动..."
sleep 10

# 12. 部署 Sub2API
echo "[12/14] 部署 Sub2API..."
mkdir -p /opt/sub2api/deploy
cd /opt/sub2api/deploy

# 下载部署脚本
curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/docker-deploy.sh -o docker-deploy.sh
chmod +x docker-deploy.sh
bash docker-deploy.sh

# 修改 docker-compose 使用本地存储
if [ -f docker-compose.yml ]; then
    # 替换为本地目录版本
    curl -sSL https://raw.githubusercontent.com/Wei-Shaw/sub2api/main/deploy/docker-compose.local.yml -o docker-compose.local.yml
    docker compose -f docker-compose.local.yml up -d
fi

# 13. 配置 SSL 自动续期
echo "[13/14] 配置 SSL 自动续期..."
cat > /etc/cron.d/certbot-renew << 'EOF'
0 0 * * * root certbot renew --quiet --deploy-hook "systemctl reload nginx"
EOF

# 14. 等待服务启动并显示状态
echo "[14/14] 验证服务状态..."
sleep 15
echo ""
echo "========================================"
echo "部署完成！"
echo "========================================"
echo ""
echo "Gitea 状态："
docker ps | grep gitea || echo "Gitea 容器状态待检查"
echo ""
echo "Sub2API 状态："
docker ps | grep sub2api || echo "Sub2API 容器状态待检查"
echo ""
echo "Nginx 状态："
systemctl status nginx --no-pager | head -5
echo ""
echo "SSL 证书状态："
certbot certificates 2>/dev/null | head -10
echo ""
echo "========================================"
echo "访问地址："
echo "- Gitea: https://tksea.top"
echo "- Sub2API: https://api.tksea.top"
echo ""
echo "后续步骤："
echo "1. 首次访问 https://tksea.top 完成 Gitea 初始化"
echo "2. 访问 https://api.tksea.top 完成 Sub2API 设置向导"
echo "3. 在腾讯云控制台添加 DNS 解析: api.tksea.top -> 43.155.133.187"
echo "========================================"