#!/usr/bin/env bash
# 只重編 + 重啟 gateway / worker / web，不動 infra、不清資料、不 migrate
# 流程：殺舊 process → 確認埠釋放 → build → 起新的
set -euo pipefail
# shellcheck source=_common.sh
source "$(cd "$(dirname "$0")" && pwd)/_common.sh"

load_env
GATEWAY_PORT="${GATEWAY_PORT:-8888}"
WEB_PORT="${WEB_PORT:-5173}"

log "=== restart apps (keep data) ==="
log "1/3 stop old gateway / worker / web…"
set +e
"$DEPLOY_DIR/scripts/stop.sh"
stop_rc=$?
set -e

if [[ "$stop_rc" -ne 0 ]] || port_in_use "$GATEWAY_PORT"; then
  leftovers="$(pids_on_port "$GATEWAY_PORT" | tr -s ' ')"
  # 再掃一次 cmdline 給使用者可複製的 sudo
  more="$(pids_by_cmdline_substr "bin/gateway" "gateway.yaml") $(pids_by_cmdline_substr "bin/worker" "gateway.yaml")"
  all="$(echo "$leftovers $more" | tr -s ' ' '\n' | grep -E '^[0-9]+$' | sort -u | tr '\n' ' ')"
  die "舊 process 沒殺乾淨，埠 :${GATEWAY_PORT} 仍被佔。請先：
  sudo kill -9 ${all:-$(echo "$leftovers")}
  make -C deploy restart"
fi

log "2/3 build…"
"$DEPLOY_DIR/scripts/build.sh"

log "3/3 start fresh…"
# start 內會再 stop 一次（雙保險）
"$DEPLOY_DIR/scripts/start.sh"

"$DEPLOY_DIR/scripts/status.sh" || true
log "=== restart done ==="
