#!/bin/bash

# Start SQL Server
/opt/mssql/bin/sqlservr &

# Wait for SQL Server to start
echo "Waiting for SQL Server to start..."
sleep 30s

# Initialize database
for i in {1..50};
do
    sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q "SELECT 1" &> /dev/null
    if [ $? -eq 0 ]
    then
        echo "SQL Server is ready"
        break
    else
        echo "SQL Server is not ready yet..."
        sleep 1
    fi
done

# Check if we should drop the database
if [ "${DROP_DATABASE,,}" = "true" ]; then
    echo "DROP_DATABASE is true. Attempting to drop database..."
    sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q "
    IF EXISTS (SELECT 1 FROM sys.databases WHERE name = 'st-database')
    BEGIN
        ALTER DATABASE [st-database] SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
        DROP DATABASE [st-database];
    END"
    if [ $? -eq 0 ]; then
        echo "Database dropped successfully."
    else
        echo "Error dropping database"
        exit 1
    fi

    # Check if database already exists and has tables
    echo "Checking if database is already initialized..."

    # First check if database exists
    DB_EXISTS=$(sqlcmd -S localhost -U sa -P $SA_PASSWORD -h -1 -Q "
    IF EXISTS (SELECT 1 FROM sys.databases WHERE name = 'st-database')
        SELECT 1
    ELSE
        SELECT 0" | tr -d '[:space:]')

    echo "Database exists check result: '$DB_EXISTS'"

    if [ "$DB_EXISTS" = "1" ]; then
        echo "Database st-database already exists and is initialized. Skipping setup."
    else
        echo "Database needs initialization. Starting setup..."
        
        # Create st-database if it doesn't exist
        echo "Creating st-database if it doesn't exist..."
        sqlcmd -S localhost -U sa -P $SA_PASSWORD -Q "IF NOT EXISTS (SELECT * FROM sys.databases WHERE name = 'st-database') CREATE DATABASE [st-database]"
        if [ $? -ne 0 ]; then
            echo "Error creating database"
            exit 1
        fi

        # Run the initialization script
        echo "Running initialization script..."
        sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i /usr/src/app/init.sql
        if [ $? -ne 0 ]; then
            echo "Error executing initialization script"
            exit 1
        fi

        # Clean up existing files in sql_objects directories
        echo "Cleaning up existing files..."
        rm -f /usr/src/app/sql_objects/*/*.sql
        rm -f /usr/src/app/sql_objects/indexes/*/*.sql
        
        # Process each schema file through the extraction scripts
        echo "Processing schema files..."
        for schema_file in /usr/src/app/schemas/*.sql
        do
            echo "Processing schema file: $schema_file"
            
            # Extract different types of SQL objects
            bash /usr/src/app/extract_tables.sh "$schema_file"
            if [ $? -ne 0 ]; then
                echo "Warning: Table extraction had some errors but continuing..."
            fi
            
            bash /usr/src/app/extract_constraints.sh "$schema_file"
            bash /usr/src/app/extract_indexes.sh "$schema_file"
            bash /usr/src/app/extract_views.sh "$schema_file"
            bash /usr/src/app/extract_procedures.sh "$schema_file"
        done

        # Function to execute SQL files from a directory
        execute_sql_files() {
            local dir=$1
            local type=$2
            
            if [ -d "$dir" ] && [ "$(ls -A $dir 2>/dev/null)" ]; then
                echo "Executing $type..."
                for sql_file in "$dir"/*.sql; do
                    if [ -f "$sql_file" ]; then
                        echo "Executing $sql_file..."
                        sqlcmd -S localhost -U sa -P $SA_PASSWORD -d st-database -i "$sql_file"
                        if [ $? -ne 0 ]; then
                            echo "Warning: Error executing $sql_file but continuing..."
                        fi
                    fi
                done
            else
                echo "No files found in $dir"
            fi
        }

        # Execute SQL objects in the correct order
        echo "Executing SQL objects in order..."

        # 1. Tables
        execute_sql_files "sql_objects/tables" "tables"

        # 2. Constraints
        execute_sql_files "sql_objects/constraints" "constraints"
        execute_sql_files "sql_objects/foreign_keys" "foreign keys"

        # 3. Indexes
        execute_sql_files "sql_objects/indexes/clustered" "clustered indexes"
        execute_sql_files "sql_objects/indexes/unique_clustered" "unique clustered indexes"
        execute_sql_files "sql_objects/indexes/nonclustered" "nonclustered indexes"

        # 4. Views
        execute_sql_files "sql_objects/views" "views"

        # 5. Stored Procedures
        execute_sql_files "sql_objects/procedures" "stored procedures"

        # Clean up
        echo "Cleaning up..."
        rm -rf sql_objects
        echo "SQL object execution completed"
    fi
fi


# Keep container running
while true; do
    sleep 1
done