#!/usr/bin/env bash
# 一次性装机脚本（跑在 epsilon 上）。
# 幂等：重跑不破坏现状。

set -euo pipefail

EPSILON_IP="112.124.27.213"
APP_USER="xiangqin"
APP_DIR="/opt/xiangqin"
UV_PYTHON_DIR="/opt/uv-python"  # 共享 Python 目录（xiangqin 用户可读）

echo "[1/7] 系统更新 + 基础包（uv 自管 Python，系统 Python 3.10 保留即可）"
apt-get update -y
apt-get install -y nginx sqlite3 cron rsync curl ca-certificates

echo "[2/7] 装 uv（官方脚本，自动带 ~/.local/bin/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 "[3/7] 创建 xiangqin app user（systemd 低权限运行）"
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 "[4/7] uv 共享 Python 路径（让 xiangqin user 能读 symlink 目标）"
mkdir -p "$UV_PYTHON_DIR"
chmod 755 "$UV_PYTHON_DIR"
export UV_PYTHON_INSTALL_DIR="$UV_PYTHON_DIR"

echo "[5/7] 装 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 "[6/7] 装 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 "[7/7] 完成。下一步 scripts/deploy.sh 发代码 → 起 systemd xiangqin"
echo "     （deploy.sh 末尾会 chown -R xiangqin:xiangqin $APP_DIR）"
