#!/bin/bash
# Nobady Box 官网一键部署到海外服务器（宝塔）
# 用法：bash ~/wwwroot-haiwai/nobody.cloud/deploy.sh
set -e
HOST=haiwaitiaobanji
DOMAIN=nobody.cloud
ROOT=/www/wwwroot/$DOMAIN
HERE="$(cd "$(dirname "$0")" && pwd)"

echo "== 1/3 上传网站文件到 $HOST:$ROOT"
tar -C "$HERE" -czf - index.html vendor Nobady-Box-V1.0-Intro.pptx articles icons sitemap.xml robots.txt | ssh "$HOST" "mkdir -p $ROOT && tar -xzf - -C $ROOT && (chown -R www:www $ROOT 2>/dev/null || true) && ls -la $ROOT $ROOT/vendor $ROOT/articles $ROOT/icons"

echo "== 2/3 检查 nginx 站点配置"
ssh "$HOST" bash -s <<REMOTE
set -e
CONF=/www/server/panel/vhost/nginx/$DOMAIN.conf
if [ -f "\$CONF" ]; then
  echo "宝塔里已有站点 $DOMAIN，沿用现有配置（含 SSL）"
else
  echo "宝塔里还没有这个站点，先写一份基础配置，网站一解析就能用 HTTP 打开"
  cat > "\$CONF" <<NGX
server {
    listen 80;
    server_name $DOMAIN www.$DOMAIN;
    root $ROOT;
    index index.html;
    location / { try_files \\\$uri \\\$uri/ /index.html; }
    location /vendor/ { expires 30d; add_header Cache-Control "public, immutable"; }
    location ~ /\. { deny all; }
    gzip on; gzip_types text/css application/javascript;
    access_log /www/wwwlogs/$DOMAIN.log;
    error_log /www/wwwlogs/$DOMAIN.error.log;
}
NGX
  NGINX=\$(command -v nginx || echo /www/server/nginx/sbin/nginx)
  \$NGINX -t && \$NGINX -s reload && echo "nginx 已重载"
fi
REMOTE

echo "== 3/3 服务器公网 IP（域名 A 记录填这个）"
ssh "$HOST" "curl -s -m 8 -4 ifconfig.me || curl -s -m 8 -4 ip.sb"; echo
echo "== 本机测试（不依赖 DNS）"
IP=$(ssh "$HOST" "curl -s -m 8 -4 ifconfig.me || curl -s -m 8 -4 ip.sb")
curl -s -o /dev/null -w "HTTP %{http_code}  %{size_download} 字节\n" -H "Host: $DOMAIN" "http://$IP/" || true
echo "完成。"
