#!/bin/bash
# 一键部署脚本 - Ubuntu 24.04
# 域名: tksea.top, 服务器: 43.155.133.187
# 使用方法: 在服务器上运行此脚本

set -e

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

# 检查 root 权限
if [ "$EUID" -ne 0 ]; then
  echo "错误: 请使用 root 用户运行此脚本"
  echo "解决方法: sudo bash deploy.sh"
  exit 1
fi

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

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

echo "[3/12] 安装 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
fi

echo "[4/12] 安装 Nginx..."
apt install -y nginx

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

echo "[6/12] 创建目录..."
mkdir -p /opt/gitea /opt/sub2api/deploy /var/www/html

echo "[7/12] 配置 Nginx..."
cat > /etc/nginx/sites-available/tksea.top << 'NGINXEOF'
server {
    listen 80;
    server_name tksea.top www.tksea.top api.tksea.top;
    root /var/www/html;
    
    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }
    
    location / {
        return 200 "Server initializing...";
    }
}
NGINXEOF

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

echo "[8/12] 获取 SSL 证书..."
certbot --nginx -d tksea.top -d www.tksea.top -d api.tksea.top --non-interactive --agree-tos --email admin@tksea.top --keep-until-expiring || true

echo "[9/12] 配置完整 Nginx 反向代理..."
cat > /etc/nginx/sites-available/tksea.top << 'NGINXEOF'
server {
    listen 80;
    server_name tksea.top www.tksea.top api.tksea.top;
    location /.well-known/acme-challenge/ { root /var/www/html; }
    location / { return 301 https://$host$request_uri; }
}

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_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;
    
    location / {
        proxy_pass http://127.0.0.1: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;
    }
}

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_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;
    
    location / {
        proxy_pass http://127.0.0.1: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;
    }
}
NGINXEOF

nginx -t && systemctl reload nginx

echo "[10/12] 部署 Gitea..."
cat > /opt/gitea/docker-compose.yml << 'GITEAEOF'
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
volumes:
  gitea-data:
GITEAEOF

cd /opt/gitea && docker compose up -d

echo "[11/12] 部署 Sub2API..."
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

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

echo ""
echo "========================================"
echo "部署完成!"
echo "========================================"
echo ""
echo "请在腾讯云控制台添加 DNS 解析:"
echo "  - 记录类型: A"
echo "  - 主机记录: api"
echo "  - 记录值: 43.155.133.187"
echo ""
echo "等待 5 分钟后访问:"
echo "  - Gitea: https://tksea.top"
echo "  - Sub2API: https://api.tksea.top"
echo "========================================"