#!/usr/bin/env bash
# 服务器上拉代码,同步 env,应用强制清仓策略并重启 PM2.
# 用法(/opt/crypto_monitor 下 root):
#   bash deploy/pull_and_restart.sh
#   bash deploy/pull_and_restart.sh --dry-run
set -euo pipefail

REPO="${REPO:-/opt/crypto_monitor}"
DRY=()
if [[ "${1:-}" == "--dry-run" ]]; then
  DRY=(--dry-run)
  echo "(dry-run mode)"
fi

cd "$REPO"
echo ">>> git pull"
git pull

echo ">>> sync common trading env (binance + okx missing keys)"
python3 scripts/sync_common_trading_env.py "${DRY[@]}"

echo ">>> force-close defaults only if missing (never overwrite manual)"
python3 scripts/sync_common_trading_env.py --apply-force-close-policy "${DRY[@]}"

if [[ ${#DRY[@]} -gt 0 ]]; then
  echo "(dry-run, skip pm2 log policy + restart)"
  exit 0
fi

echo ">>> pm2 log policy (silence leftover + 3-day retain)"
sed -i 's/\r$//' deploy/pm2_log_policy.sh 2>/dev/null || true
bash deploy/pm2_log_policy.sh

echo ">>> pm2 restart --update-env"
# --update-env：避免 PM2 dump 里残留的跨实例环境变量（如 EXCHANGE_DISPLAY_NAME）继续污染
pm2 restart crypto_gate crypto_binance crypto_okx manual-trading-hub manual-agent-gate --update-env 2>/dev/null \
  || pm2 restart crypto-monitor-gate crypto-monitor-binance crypto-monitor-okx manual-trading-hub --update-env 2>/dev/null \
  || pm2 restart all --update-env

echo ">>> FORCE_CLOSE settings"
grep -E '^FORCE_CLOSE_' crypto_monitor_gate/.env crypto_monitor_binance/.env crypto_monitor_okx/.env || true

echo "done"
