#!/usr/bin/env bash
# docker/rename-databases.sh
#
# In-place rename of the MS SQL databases from ScadaLink* → ScadaBridge*.
# Use this when you have an existing ScadaLink dev stack and want to preserve
# the seeded test data through the product rename. If you're starting fresh,
# just run `bash docker/deploy.sh` instead — infra/mssql/setup.sql now creates
# the databases with their new names directly.
#
# The MS SQL container itself (renamed scadalink-mssql → scadabridge-mssql in
# infra/docker-compose.yml) must already be running. If you also renamed the
# container, do the container rename + volume remount before this script.
#
# Usage:
#   bash docker/rename-databases.sh                 # primary databases only
#   bash docker/rename-databases.sh --include-env2  # primary + env2 databases
#
# After running, restart the application containers so EF picks up the new
# database names from the migrated connection strings:
#   bash docker/teardown.sh && bash docker/deploy.sh
#   bash docker-env2/teardown.sh && bash docker-env2/deploy.sh   # if env2

set -euo pipefail

INCLUDE_ENV2=0
if [[ "${1:-}" == "--include-env2" ]]; then
  INCLUDE_ENV2=1
fi

CONTAINER="scadabridge-mssql"
SA_PASSWORD="ScadaBridge_Dev1#"

if ! docker ps --format '{{.Names}}' | grep -q "^${CONTAINER}$"; then
  echo "Error: container '${CONTAINER}' is not running."
  echo "Start the infra stack first: cd infra && docker compose up -d"
  exit 1
fi

run_sql() {
  docker exec "$CONTAINER" /opt/mssql-tools18/bin/sqlcmd \
    -S localhost -U sa -P "$SA_PASSWORD" -C -Q "$1"
}

rename_db() {
  local old="$1"
  local new="$2"

  if ! run_sql "SELECT name FROM sys.databases WHERE name = '$old'" | grep -q "$old"; then
    echo "  $old: not present — skipping"
    return
  fi

  if run_sql "SELECT name FROM sys.databases WHERE name = '$new'" | grep -q "$new"; then
    echo "  $old → $new: target already exists — skipping"
    return
  fi

  echo "  $old → $new"
  run_sql "ALTER DATABASE [$old] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
           ALTER DATABASE [$old] MODIFY NAME = [$new];
           ALTER DATABASE [$new] SET MULTI_USER;"
}

echo "=== Renaming primary databases ==="
rename_db "ScadaLinkConfig"       "ScadaBridgeConfig"
rename_db "ScadaLinkMachineData"  "ScadaBridgeMachineData"

if [[ "$INCLUDE_ENV2" -eq 1 ]]; then
  echo
  echo "=== Renaming env2 databases ==="
  rename_db "ScadaLinkConfig2"       "ScadaBridgeConfig2"
  rename_db "ScadaLinkMachineData2"  "ScadaBridgeMachineData2"
fi

echo
echo "=== Renaming SQL login ==="
if run_sql "SELECT name FROM sys.server_principals WHERE name = 'scadalink_app'" | grep -q "scadalink_app"; then
  echo "  scadalink_app → scadabridge_app"
  run_sql "ALTER LOGIN [scadalink_app] WITH NAME = [scadabridge_app];"
  # Database-scoped user names follow the login but the rename above doesn't
  # cascade — fix them up per database.
  for db in ScadaBridgeConfig ScadaBridgeMachineData; do
    if run_sql "SELECT name FROM sys.databases WHERE name = '$db'" | grep -q "$db"; then
      run_sql "USE [$db]; IF EXISTS (SELECT 1 FROM sys.database_principals WHERE name = 'scadalink_app') ALTER USER [scadalink_app] WITH NAME = [scadabridge_app];"
    fi
  done
  if [[ "$INCLUDE_ENV2" -eq 1 ]]; then
    for db in ScadaBridgeConfig2 ScadaBridgeMachineData2; do
      if run_sql "SELECT name FROM sys.databases WHERE name = '$db'" | grep -q "$db"; then
        run_sql "USE [$db]; IF EXISTS (SELECT 1 FROM sys.database_principals WHERE name = 'scadalink_app') ALTER USER [scadalink_app] WITH NAME = [scadabridge_app];"
      fi
    done
  fi
else
  echo "  scadalink_app: not present — skipping"
fi

echo
echo "=== Done ==="
echo
echo "Next steps:"
echo "  bash docker/teardown.sh && bash docker/deploy.sh"
[[ "$INCLUDE_ENV2" -eq 1 ]] && echo "  bash docker-env2/teardown.sh && bash docker-env2/deploy.sh"
