#!/bin/bash

# Load functions
source /4server/sbin/ODOO_19/ODOO_19.lib
if [[ -z "$UUID" ]]; then
    echo "Error: UUID not set. Aborting."
    exit 1
fi

POSTGRES_HOST="${POSTGRES_HOST:-beedb}"
POSTGRES_PORT="${POSTGRES_PORT:-5432}"
POSTGRES_ADMIN_USER="${POSTGRES_ADMIN_USER:-1gtT0sf8klB9lDbYZD9}"
POSTGRES_ADMIN_PASSWORD="${POSTGRES_ADMIN_PASSWORD:-ZpSwWNafyy9GhY2gzHw}"
ODOO_DB_USER="${UUID}"
#export ODOO_DB_PASSWORD=$(echo "$SECRET" | jq -r '.psql')

BASEURL="${BASEURL:-/4server/data/$UUID}"
BACKUPURL="/4backup/$UUID"

doas docker stop "$UUID"
doas docker rm "$UUID"

if [ -n "${UUID:-}" ]; then
  echo "Removing directory: $BASEURL"
  #doas rm -rf "$BASEURL"
  echo "Removing backup directory $BACKUPURL"
  #doas rm -rf $BACKUPURL
fi


echo "Dropping PostgreSQL database: $UUID (if exists)..."
PGPASSWORD="$POSTGRES_ADMIN_PASSWORD" psql \
  -h "$POSTGRES_HOST" -U "$POSTGRES_ADMIN_USER" -p "$POSTGRES_PORT" -d postgres \
  -c "DROP DATABASE IF EXISTS \"$UUID\";"

echo "Dropping PostgreSQL user: $ODOO_DB_USER (if exists)..."
PGPASSWORD="$POSTGRES_ADMIN_PASSWORD" psql \
  -h "$POSTGRES_HOST" -U "$POSTGRES_ADMIN_USER" -p "$POSTGRES_PORT" -d postgres <<EOF
DO
\$do\$
BEGIN
   IF EXISTS (
      SELECT
      FROM   pg_catalog.pg_user
      WHERE  usename = '${ODOO_DB_USER}') THEN

      -- Drop user safely
      EXECUTE 'DROP USER "' || '${ODOO_DB_USER}' || '"';
   END IF;
END
\$do\$;
EOF

echo "✅ Database '$UUID' and user '$ODOO_DB_USER' removed (if they existed)."
