#!/usr/bin/env bash
# =====================================================================
# LogShip template cleanup — orchestrator (data truncation)
# ---------------------------------------------------------------------
# Run as root ON THE CLONE after 00-defuse.sh. Never on production.
#
#   run-cleanup.sh            # dump safety backups, truncate everything
#   run-cleanup.sh --no-dump  # skip the pg_dump safety copies
#
# Steps:
#   1. production guard
#   2. pg_dump safety copies to /root/template-cleanup/backup/
#      (DELETE THESE in the finalize phase — they contain prod data)
#   3. stop consumers (pm2 apps, iDempiere, ES sync container)
#   4. iDempiere truncation  (01-idempiere-truncate.sql) + VACUUM FULL
#   5. Strapi truncation     (02-strapi-truncate.sql) + wipe uploads dir
#   6. Elasticsearch: delete all non-system indices (sync re-creates)
#   7. restart services, restart sync (full reindex against clean DB)
#   8. log hygiene
# =====================================================================
set -euo pipefail
cd "$(dirname "$0")"

# --- 1. production guard --------------------------------------------------
if hostname | grep -q '^logship-production$'; then
  echo "FATAL: hostname is logship-production — refusing to run." >&2; exit 1
fi
if ip -4 addr show 2>/dev/null | grep -q '192\.168\.12\.72/'; then
  echo "FATAL: this host holds 192.168.12.72 (production IP) — refusing to run." >&2; exit 1
fi
echo "Guard OK: $(hostname)"

# --- 2. safety dumps ------------------------------------------------------
if [ "${1:-}" != "--no-dump" ]; then
  mkdir -p /root/template-cleanup/backup
  echo "Dumping safety copies (idempiere + strapi)..."
  sudo -u postgres pg_dump -Fc idempiere > /root/template-cleanup/backup/idempiere.pre-truncate.dump
  sudo -u postgres pg_dump -Fc strapi    > /root/template-cleanup/backup/strapi.pre-truncate.dump
  du -sh /root/template-cleanup/backup/*
  echo "NOTE: remove /root/template-cleanup/backup/ in the finalize phase!"
fi

# --- 3. stop consumers ----------------------------------------------------
pm2 stop all || true
docker stop idempiere-sync 2>/dev/null || true
systemctl stop idempiere || service idempiere stop || true
sleep 3

# --- 4. iDempiere ---------------------------------------------------------
echo "=== iDempiere truncation ==="
sudo -u postgres psql -d idempiere -f 01-idempiere-truncate.sql
echo "=== VACUUM FULL idempiere (this takes a few minutes) ==="
sudo -u postgres psql -d idempiere -c 'VACUUM FULL ANALYZE;'
sudo -u postgres psql -d idempiere -tAc "SELECT pg_size_pretty(pg_database_size('idempiere'))"

# --- 5. Strapi ------------------------------------------------------------
echo "=== Strapi truncation ==="
sudo -u postgres psql -d strapi -f 02-strapi-truncate.sql
if [ -d /opt/mediaserver/public/uploads ]; then
  find /opt/mediaserver/public/uploads -mindepth 1 -delete
  echo "uploads dir wiped: $(du -sh /opt/mediaserver/public/uploads | cut -f1)"
fi
sudo -u postgres psql -d strapi -c 'VACUUM FULL ANALYZE;' >/dev/null

# --- 6. Elasticsearch indices --------------------------------------------
echo "=== Elasticsearch cleanup ==="
if curl -sf http://127.0.0.1:9200 >/dev/null 2>&1; then
  for idx in $(curl -s 'http://127.0.0.1:9200/_cat/indices?h=index' | grep -v '^\.'); do
    echo "  deleting index $idx"
    curl -s -X DELETE "http://127.0.0.1:9200/$idx" >/dev/null
  done
else
  echo "  ES not reachable on 127.0.0.1:9200 — skipping (delete indices manually later)"
fi

# --- 7. restart -----------------------------------------------------------
systemctl start idempiere || service idempiere start || true
pm2 restart all || pm2 start all || true
docker start idempiere-sync 2>/dev/null || true
echo "services restarted; idempiere-sync will re-create/reindex ES indices from the clean DB"

# --- 8. log hygiene -------------------------------------------------------
journalctl --vacuum-time=1d >/dev/null 2>&1 || true
rm -rf /var/log/accounting/* /var/log/followup_wetzel.log \
       /opt/idempiere-server/log/* /opt/idempiere-server/heapdumps/* 2>/dev/null || true
pm2 flush >/dev/null 2>&1 || true
apt-get clean >/dev/null 2>&1 || true
rm -rf /root/.npm/_cacache /root/.cache/* 2>/dev/null || true

echo "CLEANUP COMPLETE. Review the survivor report above, then finalize:"
echo "  - verify app works (frontend login, org list, empty grids)"
echo "  - rm -rf /root/template-cleanup/backup/   (prod data!)"
echo "  - fstrim -a ; poweroff"
