#!/usr/bin/env bash
# 知命阁 Docker 部署脚本
# 用法：cd /opt/zhimingge && bash scripts/docker-deploy.sh

set -euo pipefail

APP_DIR="/opt/zhimingge"
APP_PORT="${PORT:-3130}"

cd "$APP_DIR"

if [[ ! -f .env.local ]]; then
  echo "ERROR: 缺少 .env.local，请先：cp .env.example .env.local && nano .env.local"
  exit 1
fi

echo "==> 拉取最新代码..."
git pull origin main

echo "==> 停止旧 PM2 进程（若存在）..."
pm2 stop zhimingge 2>/dev/null || true
pm2 delete zhimingge 2>/dev/null || true

echo "==> 构建 Docker 镜像..."
docker compose build

echo "==> 启动容器..."
docker compose up -d

echo "==> 状态"
docker compose ps
sleep 2
curl -s -o /dev/null -w "HTTP %{http_code}\n" "http://127.0.0.1:${APP_PORT}" || true

echo "==> 部署完成。日志：docker compose logs -f zhimingge"
