#!/bin/bash
# 修复 Nginx 配置

echo "配置 Nginx..."

cat > /etc/nginx/sites-available/tksea << 'EOF'
# HTTP 重定向
server {
    listen 80;
    server_name tksea.top www.tksea.top api.tksea.top gitea.tksea.top sub.tksea.top;
    location /.well-known/acme-challenge/ { root /var/www/html; }
    location / { return 301 https://$host$request_uri; }
}

# HTTPS - 主域名和 Gitea
server {
    listen 443 ssl http2;
    server_name tksea.top www.tksea.top gitea.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;
    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;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}

# HTTPS - API 和 Sub
server {
    listen 443 ssl http2;
    server_name api.tksea.top sub.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;
    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;
    }
}
EOF

nginx -t && systemctl reload nginx

echo "完成! 检查: sudo systemctl status nginx"