#!/bin/bash

# =========================================================================
# configure_mac_mssql_odbc.sh
# Safely registers the Microsoft ODBC Driver for macOS App Store Sandboxes
# =========================================================================

echo "========================================================="
echo "Configuring Microsoft ODBC Driver for Sandboxed Apps"
echo "========================================================="

# 1. Determine CPU Architecture & Homebrew base path
ARCH=$(uname -m)
if [ "$ARCH" = "arm64" ]; then
    BREW_PREFIX="/opt/homebrew"
    echo "Detected Apple Silicon Architecture (arm64)"
else
    BREW_PREFIX="/usr/local"
    echo "Detected Intel Architecture (x86_64)"
fi

# 2. Locate the active msodbcsql installation
MSSQL_CELLAR_DIR="$BREW_PREFIX/Cellar"
DRIVER_NAME=""
DRIVER_VERSION_DIR=""

if [ -d "$MSSQL_CELLAR_DIR/msodbcsql18" ]; then
    DRIVER_NAME="ODBC Driver 18 for SQL Server"
    DRIVER_VERSION_DIR=$(ls -d $MSSQL_CELLAR_DIR/msodbcsql18/* 2>/dev/null | tail -n 1)
    SHORT_NAME="msodbcsql18"
elif [ -d "$MSSQL_CELLAR_DIR/msodbcsql17" ]; then
    DRIVER_NAME="ODBC Driver 17 for SQL Server"
    DRIVER_VERSION_DIR=$(ls -d $MSSQL_CELLAR_DIR/msodbcsql17/* 2>/dev/null | tail -n 1)
    SHORT_NAME="msodbcsql17"
else
    echo "Error: Microsoft SQL Server ODBC Driver (v17 or v18) not found in $MSSQL_CELLAR_DIR."
    echo "Please run: brew install msodbcsql18"
    exit 1
fi

SANDBOX_DRIVER_NAME="$DRIVER_NAME (Sandboxed)"
echo "Found Driver: $DRIVER_NAME"
echo "Source Path : $DRIVER_VERSION_DIR"

# 3. Define target directories
SYSTEM_ODBC_DIR="/Library/ODBC"
TARGET_MSSQL_DIR="$SYSTEM_ODBC_DIR/mssql"
SYSTEM_ODBCINST_INI="$SYSTEM_ODBC_DIR/odbcinst.ini"

# 4. Migrate driver files to Sandbox-friendly folder with root privileges
echo "Step 1: Migrating driver files to $TARGET_MSSQL_DIR..."

# Clean old destination files to avoid cross-version contamination if re-running
if [ -d "$TARGET_MSSQL_DIR" ]; then
    echo "Wiping existing target directory to prevent resource version conflicts..."
    sudo rm -rf "$TARGET_MSSQL_DIR"
fi

sudo mkdir -p "$TARGET_MSSQL_DIR"

# Copy entire cellar structure (preserves relative .rsc resource file pathways)
sudo cp -R "$DRIVER_VERSION_DIR/." "$TARGET_MSSQL_DIR/"
sudo chmod -R 755 "$TARGET_MSSQL_DIR"
echo "Successfully mirrored driver assets into sandbox-friendly partition."

# 5. Determine correct dylib filename
DYLIB_FILE=""
if [ "$SHORT_NAME" = "msodbcsql18" ]; then
    DYLIB_FILE="libmsodbcsql.18.dylib"
else
    DYLIB_FILE="libmsodbcsql.17.dylib"
fi
TARGET_DYLIB_PATH="$TARGET_MSSQL_DIR/lib/$DYLIB_FILE"

# 6. Verify target files exist
if [ ! -f "$TARGET_DYLIB_PATH" ]; then
    echo "Error: Failed to verify compiled dylib at $TARGET_DYLIB_PATH"
    exit 1
fi

# 7. Write or update system-level odbcinst.ini
echo "Step 2: Re-registering driver in $SYSTEM_ODBCINST_INI..."
sudo mkdir -p "$SYSTEM_ODBC_DIR"
if [ ! -f "$SYSTEM_ODBCINST_INI" ]; then
    sudo touch "$SYSTEM_ODBCINST_INI"
    sudo chmod 644 "$SYSTEM_ODBCINST_INI"
fi

# Safe registry cleanup - isolates section dynamically and eliminates parsing bugs
TEMP_INI=$(mktemp)
awk -v sec="[$SANDBOX_DRIVER_NAME]" '
    $0 == sec { in_section = 1; next }
    in_section && /^\[/ { in_section = 0 }
    !in_section { print }
' "$SYSTEM_ODBCINST_INI" > "$TEMP_INI"

# Append the modern configuration block to the temp file
if [ -s "$TEMP_INI" ]; then
    echo "" >> "$TEMP_INI"
fi
echo "[$SANDBOX_DRIVER_NAME]" >> "$TEMP_INI"
echo "Description = Microsoft ODBC Driver for SQL Server (Sandboxed)" >> "$TEMP_INI"
echo "Driver = $TARGET_DYLIB_PATH" >> "$TEMP_INI"
echo "UsageCount = 1" >> "$TEMP_INI"
echo "" >> "$TEMP_INI"

# Clean multiple consecutive empty lines to keep file clean
TEMP_CLEAN=$(mktemp)
awk '
    /^[[:space:]]*$/ { if (!blank) { print ""; blank=1 } next }
    { print; blank=0 }
' "$TEMP_INI" > "$TEMP_CLEAN"

# Move config back into System Core safely
sudo cp "$TEMP_CLEAN" "$SYSTEM_ODBCINST_INI"
sudo chmod 644 "$SYSTEM_ODBCINST_INI"
rm -f "$TEMP_INI" "$TEMP_CLEAN"

echo "========================================================="
echo "Configuration Completed Successfully!"
echo "Isolated Profile registered as: '$SANDBOX_DRIVER_NAME'"
echo "Please restart your Application and select the Sandboxed driver."
echo "========================================================="
