#!/usr/bin/env bash
# 一次性装机脚本。本地跑：bash scripts/provision.sh <epsilon|alpha>
# 幂等：重跑不破坏现状。
#
# 做的事：改 hostname / 装 nginx+sqlite / 装 uv / 建 xiangqin 用户 / 装 aliyun cli /
# 写 systemd env override（按 host 分叉）。装完后跑 scripts/deploy.sh <target> 发代码。

set -euo pipefail

HOST_ARG="${1:-epsilon}"

case "$HOST_ARG" in
    epsilon) TARGET_IP="112.124.27.213"; HOSTNAME_NEW="xiangqin-epsilon" ;;
    alpha)   TARGET_IP="120.27.148.143"; HOSTNAME_NEW="xiangqin-alpha" ;;
    # 任意 IP：给 chaos migration drill 用
    [0-9]*.*[0-9]*)
        TARGET_IP="$HOST_ARG"
        HOSTNAME_NEW="xiangqin-drill-$(date +%s)"
        ;;
    *) echo "未知 host: $HOST_ARG（支持 epsilon | alpha | <IP>）" >&2; exit 1 ;;
esac

# systemd drop-in override —— 按 host 分叉
# epsilon 保持现状（unit 文件里已写死 env，不覆盖）
# alpha 要 mock 所有 provider + 独立 salt + BASE_URL 指自己
if [ "$HOST_ARG" = "alpha" ]; then
    ALPHA_SALT=$(openssl rand -hex 32)
    OVERRIDE_CONTENT=$(cat <<EOF
[Service]
Environment=XIANGQIN_SMS_PROVIDER=mock
Environment=XIANGQIN_PAYMENT_PROVIDER=mock
Environment=XIANGQIN_BASE_URL=http://${TARGET_IP}
Environment=XIANGQIN_PHONE_SALT=${ALPHA_SALT}
EOF
)
else
    OVERRIDE_CONTENT=""
fi

echo "[provision:$HOST_ARG] 目标 $TARGET_IP → hostname=$HOSTNAME_NEW"

ssh "root@${TARGET_IP}" "HOSTNAME_NEW='${HOSTNAME_NEW}' OVERRIDE_CONTENT='${OVERRIDE_CONTENT}' bash -s" <<'REMOTE'
set -euo pipefail

APP_USER="xiangqin"
APP_DIR="/opt/xiangqin"
UV_PYTHON_DIR="/opt/uv-python"

echo "[1/8] hostname"
if [ "$(hostname)" != "$HOSTNAME_NEW" ]; then
    hostnamectl set-hostname "$HOSTNAME_NEW"
fi

echo "[2/8] 系统包（uv 自管 Python，系统 Python 保留）"
apt-get update -y
apt-get install -y nginx sqlite3 cron rsync curl ca-certificates openssl

echo "[3/8] uv"
if ! command -v uv >/dev/null 2>&1; then
    curl -LsSf https://astral.sh/uv/install.sh | sh
fi
export PATH="$HOME/.local/bin:$PATH"

echo "[4/8] xiangqin app user + /opt 目录"
id -u "$APP_USER" >/dev/null 2>&1 || \
    useradd --system --no-create-home --shell /usr/sbin/nologin "$APP_USER"
mkdir -p "$APP_DIR"/{data,logs}

echo "[5/8] uv 共享 Python 目录（让 xiangqin user 能读 symlink 目标）"
mkdir -p "$UV_PYTHON_DIR"
chmod 755 "$UV_PYTHON_DIR"

echo "[6/8] aliyun cli（备份脚本用）"
if ! command -v aliyun >/dev/null 2>&1; then
    ARCH=$(uname -m | sed s/x86_64/amd64/ | sed s/aarch64/arm64/)
    cd /tmp
    curl -fsSL "https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-${ARCH}.tgz" -o aliyun-cli.tgz
    tar xzf aliyun-cli.tgz
    mv aliyun /usr/local/bin/
    rm -f aliyun-cli.tgz
fi

echo "[7/8] nginx 反向代理"
cat > /etc/nginx/sites-available/xiangqin <<'NGINX'
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;

    location / {
        proxy_pass http://127.0.0.1:8000;
        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;
    }
}
NGINX
ln -sf /etc/nginx/sites-available/xiangqin /etc/nginx/sites-enabled/xiangqin
rm -f /etc/nginx/sites-enabled/default
nginx -t && systemctl reload nginx

echo "[8/8] systemd drop-in override（如本 host 需要）"
if [ -n "$OVERRIDE_CONTENT" ]; then
    mkdir -p /etc/systemd/system/xiangqin.service.d
    echo "$OVERRIDE_CONTENT" > /etc/systemd/system/xiangqin.service.d/override.conf
    chmod 644 /etc/systemd/system/xiangqin.service.d/override.conf
    systemctl daemon-reload
    echo "  -> 写入 /etc/systemd/system/xiangqin.service.d/override.conf"
else
    echo "  -> 本 host 不需要 override（使用 unit 文件里的默认 env）"
fi

echo "[done] hostname=$(hostname)。下一步本地跑 scripts/deploy.sh 发代码"
REMOTE
