#!/bin/bash
set -e
export PATH="$HOME/.nvm/versions/node/v20.20.2/bin:$PATH"
cd /home/ross/pokerforge

echo "=== Clear active tournament ==="
node <<'NODE'
fetch('http://127.0.0.1:3030/api/tournament', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ action: 'clear' }),
})
  .then((r) => r.json())
  .then((d) => console.log('clear result', d))
  .catch((e) => console.error('clear failed', e));
NODE

sleep 1
echo "=== Tournament after clear ==="
node <<'NODE'
fetch('http://127.0.0.1:3030/api/tournament')
  .then((r) => r.json())
  .then((d) => console.log(d === null ? 'null (cleared)' : JSON.stringify(d).slice(0, 200)))
  .catch((e) => console.error(e));
NODE

echo "=== Rebuild production Next.js ==="
export NODE_ENV=production
npm run build

echo "=== Restart server ==="
# kill only pokerforge server.ts children by cwd match via /proc
for pid in $(pgrep -u ross -f 'tsx/dist/cli.mjs server.ts' || true); do
  if tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null | grep -q pokerforge; then
    echo "killing $pid"
    kill "$pid" || true
  fi
done
# also kill parent tsx if still up
sleep 2
for pid in $(pgrep -u ross -f 'pokerforge/node_modules/tsx' || true); do
  echo "killing $pid"
  kill "$pid" 2>/dev/null || true
done
sleep 2

cd /home/ross/pokerforge
export NODE_ENV=production
export PORT=3030
nohup npm run dev >> /tmp/pokerforge.log 2>&1 &
sleep 5
echo "=== Health ==="
node <<'NODE'
fetch('http://127.0.0.1:3030/')
  .then((r) => console.log('home status', r.status))
  .catch((e) => console.error(e));
NODE
ps -u ross -o pid,cmd | grep -E 'server.ts|tsx' | grep -v grep || true
echo "=== Done ==="
