#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
CONFIG_FILE="$SCRIPT_DIR/.deploy-config"

if [ ! -f "$CONFIG_FILE" ]; then
  echo "❌ 缺少 .deploy-config 文件"
  exit 1
fi

source "$CONFIG_FILE"

if ! command -v sshpass &> /dev/null; then
  echo "❌ 未安装 sshpass，请先运行: brew install hudochenkov/sshpass/sshpass"
  exit 1
fi

PASS_FILE=$(mktemp)
echo "$SERVER_PASS" > "$PASS_FILE"
trap "rm -f $PASS_FILE" EXIT

SSH_OPTS="-o StrictHostKeyChecking=no"

run_ssh() {
  sshpass -f "$PASS_FILE" ssh $SSH_OPTS "${SERVER_USER}@${SERVER_HOST}" "$@"
}

NEXTAUTH_SECRET="$(openssl rand -base64 32)"

echo ""
echo "========================================="
echo "  首次初始化服务器 ${SERVER_HOST}"
echo "========================================="
echo ""

echo "=> 创建项目目录和 uploads..."
run_ssh "mkdir -p ${REMOTE_DIR}/uploads"

echo ""
echo "=> 创建 .env 文件..."
run_ssh "cat > ${REMOTE_DIR}/.env << 'EOF'
DATABASE_URL=postgresql://nanami:Scl%40qq.com1@localhost:5432/nanamiweb?schema=public
NEXTAUTH_SECRET=${NEXTAUTH_SECRET}
NEXTAUTH_URL=http://${SERVER_HOST}:3000
ADMIN_USERNAME=admin
ADMIN_PASSWORD=admin123
EOF"

echo ""
echo "=> 验证 .env 文件..."
run_ssh "cat ${REMOTE_DIR}/.env"

echo ""
echo "========================================="
echo "  ✅ 初始化完成！"
echo "========================================="
echo ""
echo "接下来运行: ./deploy-remote.sh"
echo ""
echo "⚠️  部署成功后记得修改管理员密码："
echo "   访问 http://${SERVER_HOST}:3000/admin/login"
echo "   默认账号: admin / admin123"
echo "   登录后在「系统设置」中修改密码"
echo ""
