#!/usr/bin/env bash
# AI 建站 — 重启
# 用法：
#   ./restart.sh              # 不拉代码：停 → 构建 → 起
#   ./restart.sh --pull       # 强制对齐远程后再重启（生产一键更新）
#   ./restart.sh --no-rebuild # 重启但不强制重建镜像
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"
# shellcheck disable=SC1091
. "$ROOT/scripts/lib-aijz-deploy.sh"

REBUILD=1
DO_PULL=0
for a in "$@"; do
  case "$a" in
    --pull|--update) DO_PULL=1 ;;
    --no-pull) DO_PULL=0 ;;
    --no-rebuild) REBUILD=0 ;;
    -h|--help)
      echo "用法: $0 [--pull|--update] [--no-rebuild]"
      echo "  默认不拉代码；--pull 时 git fetch + checkout -f + reset --hard 对齐远程后重启"
      exit 0
      ;;
  esac
done

echo "========================================"
echo "  AI 建站 重启"
echo "  路径: $ROOT"
if [ "$DO_PULL" = "1" ]; then
  echo "  拉取: 是（强制对齐 ${GIT_BRANCH:-main}）"
else
  echo "  拉取: 否（加 --pull 可拉代码）"
fi
echo "========================================"

ensure_docker
ensure_env_file
export_defaults
if [ "$DO_PULL" = "1" ]; then
  git_pull_hard
fi
stack_down
sleep 1
stack_up "$REBUILD"
healthcheck
print_endpoints
