#!/usr/bin/env bash
set -euo pipefail

# 用法:
# sudo bash setup_nginx_https_proxy.sh <domain> <upstream> [email]
#
# 例子:
# sudo bash setup_nginx_https_proxy.sh api.example.com http://127.0.0.1:3000 you@example.com

DOMAIN="${1:-}"
UPSTREAM="${2:-}"
EMAIL="${3:-}"

if [[ -z "$DOMAIN" || -z "$UPSTREAM" ]]; then
  echo "用法: sudo bash $0 <domain> <upstream> [email]"
  echo "例子: sudo bash $0 api.example.com http://127.0.0.1:3000 you@example.com"
  exit 1
fi

if [[ $EUID -ne 0 ]]; then
  echo "请用 root 或 sudo 运行"
  exit 1
fi

if [[ -z "$EMAIL" ]]; then
  EMAIL="admin@${DOMAIN}"
fi

echo "==> 检查系统"
if command -v apt >/dev/null 2>&1; then
  PKG="apt"
elif command -v dnf >/dev/null 2>&1; then
  PKG="dnf"
elif command -v yum >/dev/null 2>&1; then
  PKG="yum"
else
  echo "不支持的包管理器"
  exit 1
fi

echo "==> 安装 Nginx / Certbot"
case "$PKG" in
  apt)
    apt update
    apt install -y nginx certbot python3-certbot-nginx curl
    systemctl enable nginx
    ;;
  dnf)
    dnf install -y nginx certbot python3-certbot-nginx curl
    systemctl enable nginx
    ;;
  yum)
    yum install -y epel-release || true
    yum install -y nginx certbot python3-certbot-nginx curl
    systemctl enable nginx
    ;;
esac

echo "==> 启动 Nginx"
systemctl start nginx

echo "==> 写入 HTTP 站点配置"
NGINX_CONF="/etc/nginx/conf.d/${DOMAIN}.conf"

cat > "$NGINX_CONF" <<EOF
server {
    listen 80;
    listen [::]:80;
    server_name ${DOMAIN};

    client_max_body_size 100m;

    location / {
        proxy_pass ${UPSTREAM};
        proxy_http_version 1.1;

        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";

        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}
EOF

echo "==> 测试 Nginx 配置"
nginx -t

echo "==> 重载 Nginx"
systemctl reload nginx

echo "==> 申请 HTTPS 证书"
certbot --nginx \
  -d "${DOMAIN}" \
  --non-interactive \
  --agree-tos \
  -m "${EMAIL}" \
  --redirect

echo "==> 再次检查 Nginx"
nginx -t
systemctl reload nginx

echo

echo "完成。"
echo "域名: ${DOMAIN}"
echo "反代到: ${UPSTREAM}"
echo "证书邮箱: ${EMAIL}"
echo "测试地址: https://${DOMAIN}"
