#!/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 policy: gate=ON, binance/okx=OFF"
python3 scripts/sync_common_trading_env.py --apply-force-close-policy "${DRY[@]}"

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

echo ">>> pm2 restart"
pm2 restart crypto_gate crypto_binance crypto_okx manual-trading-hub manual-agent-gate 2>/dev/null \
  || pm2 restart crypto-monitor-gate crypto-monitor-binance crypto-monitor-okx manual-trading-hub 2>/dev/null \
  || pm2 restart all

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

echo "done"
