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

# ===== EternalAI 服务器初始化脚本 =====
# 首次部署时在服务器上运行，自动检测并安装所有依赖
# 用法: bash deploy/setup-server.sh
#
# 可通过环境变量自定义:
#   DB_NAME=eternalai  数据库名
#   DB_USER=eternalai  数据库用户
#   DB_PASS=xxx        数据库密码（必填，否则自动生成）

# ---- 颜色输出 ----
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

info()  { echo -e "${GREEN}[INFO]${NC} $1"; }
warn()  { echo -e "${YELLOW}[WARN]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }

# ---- 配置 ----
DB_NAME="${DB_NAME:-eternalai}"
DB_USER="${DB_USER:-eternalai}"
DB_PASS="${DB_PASS:-$(openssl rand -base64 24 | tr -d '/+=' | head -c 24)}"
APP_DIR="$(cd "$(dirname "$0")/.." && pwd)"
NODE_VERSION="20"

info "应用目录: $APP_DIR"
info "数据库: $DB_NAME (用户: $DB_USER)"

# ---- 检测 OS ----
if [[ -f /etc/os-release ]]; then
  . /etc/os-release
  OS_ID="$ID"
  info "检测到操作系统: $PRETTY_NAME"
else
  error "无法检测操作系统，仅支持 Ubuntu/Debian/CentOS"
  exit 1
fi

# ---- 安装 Node.js ----
if ! command -v node &>/dev/null; then
  info "安装 Node.js $NODE_VERSION LTS..."
  if [[ "$OS_ID" == "ubuntu" || "$OS_ID" == "debian" ]]; then
    curl -fsSL "https://deb.nodesource.com/setup_${NODE_VERSION}.x" | sudo -E bash -
    sudo apt-get install -y nodejs
  elif [[ "$OS_ID" == "centos" || "$OS_ID" == "rhel" || "$OS_ID" == "rocky" ]]; then
    curl -fsSL "https://rpm.nodesource.com/setup_${NODE_VERSION}.x" | sudo -E bash -
    sudo yum install -y nodejs
  else
    error "不支持的操作系统: $OS_ID，请手动安装 Node.js $NODE_VERSION"
    exit 1
  fi
  info "Node.js 安装完成: $(node -v)"
else
  info "Node.js 已安装: $(node -v)"
  NODE_MAJOR=$(node -v | sed 's/v\([0-9]*\).*/\1/')
  if [[ "$NODE_MAJOR" -lt 18 ]]; then
    warn "Node.js 版本过低 (当前 $(node -v))，建议升级到 $NODE_VERSION LTS"
  fi
fi

# ---- 安装 PM2 ----
if ! command -v pm2 &>/dev/null; then
  info "安装 PM2..."
  sudo npm install -g pm2
  info "PM2 安装完成: $(pm2 -v)"
else
  info "PM2 已安装: $(pm2 -v)"
fi

# ---- 安装 PostgreSQL ----
if ! command -v psql &>/dev/null; then
  info "安装 PostgreSQL 15..."
  if [[ "$OS_ID" == "ubuntu" || "$OS_ID" == "debian" ]]; then
    sudo apt-get install -y ca-certificates curl gnupg lsb-release
    sudo install -m 0755 -d /etc/apt/keyrings
    curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo gpg --dearmor -o /etc/apt/keyrings/postgresql.gpg
    echo "deb [signed-by=/etc/apt/keyrings/postgresql.gpg] http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list
    sudo apt-get update
    sudo apt-get install -y postgresql-15
  elif [[ "$OS_ID" == "centos" || "$OS_ID" == "rhel" || "$OS_ID" == "rocky" ]]; then
    sudo yum install -y "https://download.postgresql.org/pub/repos/yum/reporpms/EL-$(rpm -E %{rhel})-x86_64/pgdg-redhat-repo-latest.noarch.rpm"
    sudo yum install -y postgresql15-server postgresql15
    sudo /usr/pgsql-15/bin/postgresql-15-setup initdb
  else
    error "不支持的操作系统: $OS_ID，请手动安装 PostgreSQL 15"
    exit 1
  fi
  info "PostgreSQL 安装完成"
else
  info "PostgreSQL 已安装: $(psql --version)"
fi

# ---- 启动 PostgreSQL ----
if ! sudo systemctl is-active --quiet postgresql; then
  info "启动 PostgreSQL 服务..."
  sudo systemctl enable postgresql
  sudo systemctl start postgresql
fi

# ---- 创建数据库和用户 ----
info "创建数据库 $DB_NAME 和用户 $DB_USER..."
sudo -u postgres psql -tc "SELECT 1 FROM pg_roles WHERE rolname='$DB_USER'" | grep -q 1 || {
  sudo -u postgres psql -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS';"
  info "数据库用户 $DB_USER 已创建"
}
sudo -u postgres psql -tc "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'" | grep -q 1 || {
  sudo -u postgres psql -c "CREATE DATABASE $DB_NAME OWNER $DB_USER;"
  info "数据库 $DB_NAME 已创建"
}
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE $DB_NAME TO $DB_USER;" >/dev/null

# 确保 PostgreSQL 对 pg_hba.conf 允许密码认证
PG_HBA=$(sudo -u postgres psql -t -c "SHOW hba_file" | xargs)
if [[ -f "$PG_HBA" ]]; then
  if ! sudo grep -q "$DB_USER" "$PG_HBA" 2>/dev/null; then
    warn "如果连接数据库失败，请检查 $PG_HBA 是否允许 md5/scram-sha-256 认证"
    warn "添加: host $DB_NAME $DB_USER 127.0.0.1/32 scram-sha-256"
  fi
fi

# ---- 安装 Nginx ----
if ! command -v nginx &>/dev/null; then
  info "安装 Nginx..."
  if [[ "$OS_ID" == "ubuntu" || "$OS_ID" == "debian" ]]; then
    sudo apt-get install -y nginx
  elif [[ "$OS_ID" == "centos" || "$OS_ID" == "rhel" || "$OS_ID" == "rocky" ]]; then
    sudo yum install -y nginx
  fi
  info "Nginx 安装完成: $(nginx -v 2>&1)"
else
  info "Nginx 已安装: $(nginx -v 2>&1)"
fi

if ! sudo systemctl is-active --quiet nginx; then
  sudo systemctl enable nginx
  sudo systemctl start nginx
fi

# ---- 创建 .env 文件 ----
ENV_FILE="$APP_DIR/.env"
if [[ ! -f "$ENV_FILE" ]]; then
  info "创建 .env 文件..."
  JWT_SECRET=$(openssl rand -base64 48)
  cat > "$ENV_FILE" <<EOF
DATABASE_URL="postgresql://$DB_USER:$DB_PASS@localhost:5432/$DB_NAME"
JWT_SECRET="$JWT_SECRET"
PORT=3001
EOF
  info ".env 文件已创建（请妥善保管数据库密码和 JWT 密钥）"
  echo ""
  echo "=============================="
  echo " 数据库密码: $DB_PASS"
  echo " JWT 密钥已自动生成"
  echo "=============================="
  echo ""
else
  info ".env 文件已存在，跳过创建"
fi

# ---- 创建日志目录 ----
mkdir -p "$APP_DIR/logs"

# ---- 安装项目依赖 ----
info "安装项目依赖..."
cd "$APP_DIR"
npm install

# ---- 生成 Prisma Client ----
info "生成 Prisma Client..."
npx prisma generate

# ---- 推送数据库 Schema ----
info "推送数据库 Schema..."
npx prisma db push

# ---- 配置 PM2 开机自启 ----
info "配置 PM2 开机自启..."
pm2 start ecosystem.config.js || true
pm2 save
pm2 startup systemd -u "$(whoami)" --hp "$HOME" 2>/dev/null | grep "sudo" | bash || true

# ---- 完成 ----
echo ""
info "============================================"
info " 服务器初始化完成!"
info "============================================"
echo ""
echo "下一步:"
echo "  1. 配置 Nginx 反向代理（参考 deploy/nginx.conf）"
echo "  2. 检查应用状态: pm2 status"
echo "  3. 查看日志: pm2 logs eternalai"
echo "  4. 访问应用: http://localhost:3001"
echo ""
