#!/usr/bin/env bash
# ============================================================
# Agent ORDS security ADB local-only executable example.
#
# This script does not call RDS, DB Link, Postgres, or MySQL.
# It creates local ADB tables/views and verifies VPD + DDS.
# ============================================================
set -Eeuo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT"

if [[ ! -f "$ROOT/.env" ]]; then
  echo "[FAIL] .env not found. Copy .env.example to .env and fill ADB_* values." >&2
  exit 1
fi

set -a
# shellcheck disable=SC1091
. "$ROOT/.env"
set +a

run_admin() {
  local sql_file="$1"
  echo
  echo "[ADMIN] @$sql_file"
  sqlplus -S -L "${ADB_USER}/${ADB_PASSWORD}@${ADB_TNS}" @"$sql_file"
}

run_as() {
  local user="$1" password="$2" sql_file="$3"
  echo
  echo "[$user] @$sql_file"
  sqlplus -S -L "${user}/${password}@${ADB_TNS}" @"$sql_file"
}

run_admin "$ROOT/sql/adb/16_agent_ords_security_local_cleanup.sql"
run_admin "$ROOT/sql/adb/17_agent_ords_security_local_vpd_setup.sql"
run_admin "$ROOT/sql/adb/19_agent_ords_security_local_dds_setup.sql"
run_admin "$ROOT/sql/adb/21_agent_ords_security_ords_enable_schema.sql"
run_as "cb_ords" "CbOrdS#2026Local1" "$ROOT/sql/adb/22_agent_ords_security_ords_handler_setup.sql"
run_admin "$ROOT/sql/adb/24_agent_ords_security_inventory.sql"

run_as "cb_ords" "CbOrdS#2026Local1" "$ROOT/sql/adb/18_agent_ords_security_local_vpd_test.sql"
run_as "cb_ords" "CbOrdS#2026Local1" "$ROOT/sql/adb/23_agent_ords_security_ords_handler_test.sql"

run_as '"cb_dds_hr"' "CbDds#Hr2026Local1" "$ROOT/sql/adb/20_agent_ords_security_local_dds_test.sql"
run_as '"cb_dds_fin"' "CbDds#Fin2026Local1" "$ROOT/sql/adb/20_agent_ords_security_local_dds_test.sql"
run_as '"cb_dds_all"' "CbDds#All2026Local1" "$ROOT/sql/adb/20_agent_ords_security_local_dds_test.sql"
run_as '"cb_dds_none"' "CbDds#None2026Local1" "$ROOT/sql/adb/20_agent_ords_security_local_dds_test.sql"

echo
echo "[OK] Agent ORDS security ADB local-only VPD + DDS executable example complete"
