#!/bin/bash
set -e

echo "==== [1] Terminating all vexplor sessions ===="
docker exec -i invyone-db psql -U postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname LIKE '%vexplor%' AND pid <> pg_backend_pid();" 2>&1 | tail -3

sleep 2

echo ""
echo "==== [2] Dropping 6 test databases ===="
for db in newtest5_vexplor newtest6_vexplor test002_vexplor test07_vexplor test08_vexplor wace_vexplor; do
  echo "  - Dropping $db"
  docker exec -i invyone-db psql -U postgres -c "DROP DATABASE IF EXISTS \"$db\";" 2>&1
done

echo ""
echo "==== [3] Deleting 8 test company records ===="
docker exec -i invyone-db psql -U postgres -d vexplor -c "DELETE FROM COMPANY_MNG WHERE COMPANY_CODE IN ('NEWTEST03','NEWTEST05','NEWTEST06','TEST07','TEST08','TEST002','WACE11','COMPANY_10');" 2>&1

echo ""
echo "==== [4] RENAME vexplor -> invyone ===="
docker exec -i invyone-db psql -U postgres -c "ALTER DATABASE vexplor RENAME TO invyone;" 2>&1

echo ""
echo "==== [5] Final DB list ===="
docker exec -i invyone-db psql -U postgres -l | grep -v template | grep -v postgres

echo ""
echo "==== [6] Company count in invyone ===="
docker exec -i invyone-db psql -U postgres -d invyone -tAc "SELECT COUNT(*) || ' companies in COMPANY_MNG' FROM COMPANY_MNG;"

echo ""
echo "==== [7] Scale backend back to 1 ===="
KUBECONFIG=/home/chpark/.kube/config kubectl scale deployment backend-spring --replicas=1 -n invyone

echo ""
echo "==== DONE ===="
