#!/bin/bash

BASE_DIR="/etc/nginx/download/appinstall/windows"
TEMPLATE="sql-template.ps1"

# SQL Server version mapping
declare -A SQL_VERSION_MAP=(
  ["express_2022"]="SQL_2022_Express_X64"
  ["express_2019"]="SQL_2019_Express_X64"
  ["express_2017"]="SQL_2017_Express_X64"
  ["express_2016"]="SQL_2016_Express_X64"
  ["express_2014"]="SQL_2014_Express_X64"
  ["express_2012"]="SQL_2012_Exp_SP1_x64"
)

# Check if template exists
if [ ! -f "$TEMPLATE" ]; then
    echo "ERROR: Template file $TEMPLATE does not exist"
    exit 1
fi

# Scan windows directory
for OS_DIR in "$BASE_DIR"/*; do
    [ -d "$OS_DIR" ] || continue

    DIR_NAME=$(basename "$OS_DIR")
    echo "Processing directory: $DIR_NAME"

    # Create sql_server subdirectory
    SQL_DIR="${OS_DIR}/sql_server"
    mkdir -p "$SQL_DIR"

    # Generate PS1 scripts for each SQL version
    for VER_KEY in "${!SQL_VERSION_MAP[@]}"; do
        SQL_VERSION="${SQL_VERSION_MAP[$VER_KEY]}"

        OUT_FILE="${SQL_DIR}/${DIR_NAME}-sql_server-${VER_KEY}.ps1"
        echo "  Generating $OUT_FILE (SQLVersion=$SQL_VERSION)"

        sed \
          -e "s/^\$SQLVersion *= *.*/\$SQLVersion = \"${SQL_VERSION}\"/" \
          "$TEMPLATE" > "$OUT_FILE"
    done
done

echo "All SQL Server installation scripts have been generated successfully."
