#!/bin/bash
# 在 shihe 上开通 https://nobadybox.imai.fan （只新增文件，不改已有站点、不装软件）
# 用法：在 Mac 上运行  bash 开通nobadybox域名.sh
set -e
ssh shihe 'bash -s' <<'REMOTE'
set -e
D=nobadybox.imai.fan
F=/www/server/panel/vhost/nginx/$D.conf
CB=/opt/octop/certbot-venv/bin/certbot
[ -e "$F" ] && { echo "已存在 $F，停止"; exit 1; }

# 1) 先上纯 HTTP，供证书验证
cat > $F <<EOF
# NobadyBox 项目文件下载站 $D（2026-10-28 新增）
server
{
    listen 80;
    server_name $D;
    root /www/wwwroot/nobadybox-files;
    index index.html;
    charset utf-8;
    charset_types text/plain text/markdown text/css application/javascript;
    location ^~ /.well-known/acme-challenge/ { default_type text/plain; try_files \$uri =404; }
    location / { autoindex on; autoindex_exact_size off; autoindex_localtime on; }
    access_log /www/wwwlogs/$D.access.log;
    error_log /www/wwwlogs/$D.error.log;
}
EOF
nginx -t && nginx -s reload

# 2) 签证书（webroot，Let's Encrypt，沿用 copy.imai.fan 的做法）
$CB certonly --webroot -w /www/wwwroot/nobadybox-files -d $D --cert-name $D \
  --key-type ecdsa --non-interactive --agree-tos --register-unsafely-without-email --keep-until-expiring

# 3) 换成 HTTPS + 80 跳转
cat > $F <<EOF
# NobadyBox 项目文件下载站 $D（2026-10-28 新增，证书 certbot webroot，续期 nobadybox-cert-renew.timer）
server
{
    listen 80;
    server_name $D;
    root /www/wwwroot/nobadybox-files;
    location ^~ /.well-known/acme-challenge/ { default_type text/plain; try_files \$uri =404; }
    location / { return 301 https://\$host\$request_uri; }
    access_log /www/wwwlogs/$D.access.log;
    error_log /www/wwwlogs/$D.error.log;
}
server
{
    listen 443 ssl http2;
    server_name $D;
    ssl_certificate /etc/letsencrypt/live/$D/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/$D/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    root /www/wwwroot/nobadybox-files;
    index index.html;
    charset utf-8;
    charset_types text/plain text/markdown text/css application/javascript;
    location / { autoindex on; autoindex_exact_size off; autoindex_localtime on; }
    access_log /www/wwwlogs/$D.access.log;
    error_log /www/wwwlogs/$D.error.log;
}
EOF
nginx -t && nginx -s reload

# 4) 自动续期（新增 systemd 定时器，和 copy-cert-renew 同样写法）
cat > /etc/systemd/system/nobadybox-cert-renew.service <<EOF
[Unit]
Description=Renew $D HTTPS certificate
After=network-online.target
[Service]
Type=oneshot
ExecStart=$CB renew --quiet --cert-name $D --deploy-hook "/usr/bin/nginx -t && /usr/bin/nginx -s reload"
EOF
cat > /etc/systemd/system/nobadybox-cert-renew.timer <<EOF
[Unit]
Description=Check $D certificate renewal twice daily
[Timer]
OnCalendar=*-*-* 04,16:50:00
RandomizedDelaySec=1800
Persistent=true
[Install]
WantedBy=timers.target
EOF
systemctl daemon-reload && systemctl enable --now nobadybox-cert-renew.timer
openssl x509 -in /etc/letsencrypt/live/$D/fullchain.pem -noout -enddate
echo "完成"
REMOTE
curl -sI https://nobadybox.imai.fan/ | head -1
