#!/usr/bin/env bash
# docker-dev cluster-seed entrypoint. Applies the idempotent row seed.
#
# This container does NOT run EF migrations — sqlcmd can't execute the migration
# script cleanly (it has CREATE PROCEDURE inside IF NOT EXISTS BEGIN ... END
# blocks; procs must be the first statement in their batch). The schema is owned
# by the `migrator` Compose service (dotnet ef), which this seed depends on via
# `service_completed_successfully` — so by the time we run, migrations are fully
# applied. The dbo.ServerCluster wait below is therefore just a fast sanity check.
# Re-runs are safe: every insert in seed-clusters.sql is IF NOT EXISTS-guarded.

set -euo pipefail

SQLCMD="/opt/mssql-tools/bin/sqlcmd"
SERVER="${SQL_HOST:-sql},1433"
USER="${SQL_USER:-sa}"
PASS="${SQL_PASSWORD:-OtOpcUa!Dev123}"
DB="${SQL_DATABASE:-OtOpcUa}"

run_sql_in() {
    local target_db="$1"; shift
    # -I forces SET QUOTED_IDENTIFIER ON (needed for filtered indexes if you
    # ever extend this script to touch them).
    "$SQLCMD" -S "$SERVER" -U "$USER" -P "$PASS" -d "$target_db" -b -h -1 -I "$@"
}

echo "[cluster-seed] waiting for SQL Server to accept connections..."
until run_sql_in master -Q "SELECT 1" >/dev/null 2>&1; do
    sleep 2
done
echo "[cluster-seed] SQL Server up."

echo "[cluster-seed] verifying ${DB} schema (dbo.ServerCluster) is present (migrator should have applied it)..."
until run_sql_in "$DB" -Q "IF OBJECT_ID('dbo.ServerCluster') IS NULL THROW 50001, 'missing', 1; SELECT 1" >/dev/null 2>&1; do
    sleep 3
done
echo "[cluster-seed] schema ready."

echo "[cluster-seed] applying seed-clusters.sql (ServerCluster + ClusterNode rows)..."
run_sql_in "$DB" -i /seed/seed-clusters.sql
echo "[cluster-seed] done."
