#!/bin/bash
# sqlmorph — MSSQL T-SQL install script.  Built by Oninit LLC.
#
# Installs every *.sql file in the current directory (or BUNDLE_DIR) into
# the target MSSQL database via sqlcmd. The emitted .sql files already
# carry the pre-2016 compatibility preamble (`IF OBJECT_ID DROP` + `GO`
# + `CREATE OR ALTER`) so reruns are safe.
#
# Usage:
#   ./install.mssql.sh -d <db> -S <server> -U <user> -P <password>
#   ./install.mssql.sh -d mydb -S localhost -U sa -P secret
#
# Or via env:
#   MSSQL_DB=mydb MSSQL_SERVER=localhost MSSQL_USER=sa \
#       MSSQL_PWD=secret ./install.mssql.sh
#
# Defaults: -S localhost  -U sa  -d sqlmorph_test
set -euo pipefail

DB="${MSSQL_DB:-sqlmorph_test}"
SERVER="${MSSQL_SERVER:-localhost}"
USER="${MSSQL_USER:-sa}"
PWD="${MSSQL_PWD:-}"
BUNDLE_DIR="${BUNDLE_DIR:-.}"

while [[ $# -gt 0 ]]; do
    case "$1" in
        -d) DB="$2"; shift 2 ;;
        -S) SERVER="$2"; shift 2 ;;
        -U) USER="$2"; shift 2 ;;
        -P) PWD="$2"; shift 2 ;;
        -h|--help) sed -n '2,18p' "$0" | sed 's/^# \?//' ; exit 0 ;;
        *) echo "unknown arg: $1" >&2 ; exit 2 ;;
    esac
done

if [[ -z "$PWD" ]]; then
    echo "MSSQL password required (set MSSQL_PWD env var or pass -P)." >&2
    exit 2
fi

if ! command -v sqlcmd >/dev/null 2>&1; then
    echo "sqlcmd not on PATH — install mssql-tools or run inside the MSSQL container." >&2
    exit 2
fi

shopt -s nullglob
files=("$BUNDLE_DIR"/*_install.sql "$BUNDLE_DIR"/*.sql)
# Drop duplicates (a file matches both globs if named like *_install.sql).
declare -A seen
ordered=()
for f in "${files[@]}"; do
    [[ -z "${seen[$f]:-}" ]] || continue
    seen[$f]=1
    ordered+=("$f")
done

if [[ ${#ordered[@]} -eq 0 ]]; then
    echo "no *.sql files found in $BUNDLE_DIR" >&2
    exit 2
fi

echo "==> sqlmorph MSSQL install (db=$DB, server=$SERVER, user=$USER)"
fail=0
for f in "${ordered[@]}"; do
    echo "    sqlcmd -i $f"
    if ! sqlcmd -S "$SERVER" -U "$USER" -P "$PWD" -C -d "$DB" -b -i "$f"; then
        echo "    FAILED: $f" >&2
        fail=1
    fi
done
echo "==> $( [ $fail -eq 0 ] && echo 'ok' || echo 'errors above' )"
exit $fail
