#!/bin/sh

# ============================================================================
# Snowflake ODBC Driver Flatpak Configurator
# ============================================================================
# Description: This script finds a system-installed Snowflake ODBC driver and
#              configures a sandboxed copy for use with Flatpak applications.
#              It requires the official Snowflake ODBC driver to be installed
#              on the system first.
# ============================================================================

# --- Configuration Constants ---
ODBC_INST_FILE="/etc/odbcinst.ini"
SYSTEM_DRIVER_SECTION="SnowflakeDSIIDriver"
FLATPAK_DRIVER_SECTION="SnowflakeDSIIDriverFlatpak"
FLATPAK_DEST_BASE="$HOME/.config/navicat/ODBC"
FLATPAK_DEST_DIR_NAME="snowflake"
FLATPAK_DEST_PATH="$FLATPAK_DEST_BASE/$FLATPAK_DEST_DIR_NAME"

# --- Color Definitions ---
ORANGE='\033[0;33m'
NC='\033[0m' # No Color

# --- Help Message ---
show_help() {
  echo "Usage: $0"
  echo "Configure a sandboxed Snowflake ODBC driver for Flatpak applications."
  echo
  echo "This script requires that the official Snowflake ODBC driver is already"
  echo "installed and registered in '$ODBC_INST_FILE'."
  exit 0
}

# --- Argument Parser ---
if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  show_help
fi

# ============================================================================
# User Confirmation
# ============================================================================
printf "\nThis script finds a system-installed Snowflake ODBC driver and configures a sandboxed copy for use with Flatpak applications.\n"
printf "${ORANGE}It will use 'sudo' to modify system configuration files in '/etc'.${NC}\n"
printf "You will be prompted for your password to proceed.\n\n"
printf "Press [Enter] to continue or Ctrl+C to cancel... "
read -r _ # Wait for user input, store it in a throwaway variable

echo
echo

# ============================================================================
# Phase 1: Pre-run Checks
# ============================================================================
echo "--- Phase 1: Pre-run Checks ---"
REQUIRED_TOOLS="grep awk sed cp mkdir dirname tee sudo ldconfig"
for tool in $REQUIRED_TOOLS; do
  if ! command -v "$tool" >/dev/null 2>&1; then
    echo "ERROR: Missing required tool: $tool"
    exit 1
  fi
done
echo "All required tools are present."
echo

# ============================================================================
# Phase 2: Find the System-Installed Snowflake ODBC Driver
# ============================================================================
echo "--- Phase 2: Finding System-Installed Snowflake Driver ---"
if ! grep -q "^\\[$SYSTEM_DRIVER_SECTION\\]" "$ODBC_INST_FILE" 2>/dev/null; then
    echo "ERROR: The '$SYSTEM_DRIVER_SECTION' entry was not found in '$ODBC_INST_FILE'."
    echo "Please install the official Snowflake ODBC driver first before running this script."
    exit 1
fi
echo "Found system-installed '$SYSTEM_DRIVER_SECTION' driver."
echo

# ============================================================================
# Phase 3: Find and Register the ODBC Driver Path for Flatpak
# ============================================================================
echo "--- Phase 3: Configuring Driver for Flatpak ---"

# Parse the driver library path from the system odbcinst.ini
DRIVER_LIB_PATH=$(awk -F= -v section="[$SYSTEM_DRIVER_SECTION]" '
    $0 == section { in_section=1; next }
    $0 ~ /^\[/ { if (in_section) exit }
    in_section && tolower($1) ~ /^[[:space:]]*driver[[:space:]]*/ { print $2; exit }
' "$ODBC_INST_FILE" | xargs) # xargs trims whitespace

if [ -z "$DRIVER_LIB_PATH" ]; then
    echo "ERROR: Could not parse the 'Driver' path from the '$SYSTEM_DRIVER_SECTION' section."
    exit 1
fi
echo "Parsed system driver library path: $DRIVER_LIB_PATH"

# Determine the source root directory (the parent 'snowflake' directory)
# This sed command finds the path up to and including '/snowflake'
SOURCE_ROOT_PATH=$(echo "$DRIVER_LIB_PATH" | sed -n 's|\(.*\/snowflake\)\/.*|\1|p')

if [ -z "$SOURCE_ROOT_PATH" ] || [ ! -d "$SOURCE_ROOT_PATH" ]; then
    echo "ERROR: Could not determine the root 'snowflake' source directory from path: $DRIVER_LIB_PATH"
    echo "Expected a path structure like '/path/to/snowflake/...'. Please check the driver installation."
    exit 1
fi
echo "Determined source root path: $SOURCE_ROOT_PATH"

# Create destination directory for Flatpak
echo "Creating destination directory: $FLATPAK_DEST_PATH"
mkdir -p "$FLATPAK_DEST_PATH"
if [ $? -ne 0 ]; then
    echo "ERROR: Failed to create destination directory."
    exit 1
fi

# Copy all files from source to destination
echo "Copying files from $SOURCE_ROOT_PATH to $FLATPAK_DEST_PATH..."
# cp -rT copies the *contents* of the source directory into the destination directory.
cp -rT "$SOURCE_ROOT_PATH/" "$FLATPAK_DEST_PATH/"
if [ $? -ne 0 ]; then
    echo "ERROR: Failed to copy driver files."
    exit 1
fi
echo "Files copied successfully."
echo

# Register the new Flatpak ODBC entry in the system /etc/odbcinst.ini
echo "Registering '$FLATPAK_DRIVER_SECTION' in $ODBC_INST_FILE (requires sudo)..."

# Get the original section content, stopping at the next section
ORIGINAL_SECTION_CONTENT=$(awk -v section="[$SYSTEM_DRIVER_SECTION]" '
    $0 == section { in_section=1; next }
    $0 ~ /^\[/ { if (in_section) exit }
    in_section { print }
' "$ODBC_INST_FILE")

# Calculate the new driver library path relative to the destination
RELATIVE_LIB_PATH=${DRIVER_LIB_PATH#$SOURCE_ROOT_PATH}
FLATPAK_DRIVER_LIB_PATH="$FLATPAK_DEST_PATH$RELATIVE_LIB_PATH"

# Replace the Driver path in the content we captured
FLATPAK_SECTION_CONTENT=$(echo "$ORIGINAL_SECTION_CONTENT" | sed "s#Driver=.*#Driver=$FLATPAK_DRIVER_LIB_PATH#")

# Safely remove the old Flatpak entry from system odbcinst.ini before adding a new one
if sudo grep -q "^\\[$FLATPAK_DRIVER_SECTION\\]" "$ODBC_INST_FILE" 2>/dev/null; then
    echo "Removing previous '$FLATPAK_DRIVER_SECTION' entry..."
    TEMP_FILE=$(mktemp)
    # Use awk to filter out the entire section
    sudo awk -v section="[$FLATPAK_DRIVER_SECTION]" '
        $0 == section { in_section = 1; next }
        $0 ~ /^\[/ { in_section = 0 }
        !in_section { print }
    ' "$ODBC_INST_FILE" > "$TEMP_FILE" && sudo mv "$TEMP_FILE" "$ODBC_INST_FILE"
fi


# Append the new section
{
  printf "\n[%s]\n" "$FLATPAK_DRIVER_SECTION"
  printf "%s\n" "$FLATPAK_SECTION_CONTENT"
} | sudo tee -a "$ODBC_INST_FILE" > /dev/null
echo "Driver registered for Flatpak in system configuration."
echo

# Modify the simba.snowflake.ini for the Flatpak environment
SIMBA_INI_PATH="$FLATPAK_DEST_PATH/odbc/lib/simba.snowflake.ini"
if [ ! -f "$SIMBA_INI_PATH" ]; then
    echo "WARNING: Could not find '$SIMBA_INI_PATH'. Skipping modification."
else
    echo "Modifying '$SIMBA_INI_PATH'..."
    
    # Dynamically find the true path of libodbcinst.so
    echo "Searching for libodbcinst.so path..."
    # ldconfig -p prints the cache. We grep for the library and extract the full path.
    ODBCINST_LIB_PATH=$(ldconfig -p | grep 'libodbcinst.so' | awk '{print $NF}' | head -n 1)

    if [ -z "$ODBCINST_LIB_PATH" ]; then
        echo "WARNING: Could not dynamically find 'libodbcinst.so'. Using a fallback path."
        # Fallback to a common default if not found
        FLATPAK_ODBCINST_LIB_PATH="/run/host/usr/lib/x86_64-linux-gnu/libodbcinst.so"
    else
        echo "Found libodbcinst.so at: $ODBCINST_LIB_PATH"
        # The path inside the config file must point to the host system from within the Flatpak sandbox
        FLATPAK_ODBCINST_LIB_PATH="/run/host$ODBCINST_LIB_PATH"
    fi
    
    # Using '#' as sed delimiter because paths contain '/'.
    sed -i.bak "s#ErrorMessagesPath=.*#ErrorMessagesPath=$FLATPAK_DEST_PATH/odbc/ErrorMessages#" "$SIMBA_INI_PATH"
    sed -i "s#ODBCInstLib=.*#ODBCInstLib=$FLATPAK_ODBCINST_LIB_PATH#" "$SIMBA_INI_PATH"
    sed -i "s#CABundleFile=.*#CABundleFile=$FLATPAK_DEST_PATH/odbc/lib/cacert.pem#" "$SIMBA_INI_PATH"
    echo "'$SIMBA_INI_PATH' modified."
fi
echo

# ============================================================================
# Phase 4: Configure System Linker for Flatpak driver
# ============================================================================
echo "--- Phase 4: Configure System Linker ---"
echo "Updating system linker configuration for the new Flatpak driver (requires sudo)..."
# Get the directory of the new Flatpak driver library
FLATPAK_LIB_DIR=$(dirname "$FLATPAK_DRIVER_LIB_PATH")
CONF_FILE="/etc/ld.so.conf.d/snowflake_odbc_flatpak.conf"

echo "$FLATPAK_LIB_DIR" | sudo tee "$CONF_FILE" >/dev/null
sudo ldconfig
echo "Linker configuration updated."
echo

# ============================================================================
# Phase 5: Summary
# ============================================================================
echo "--- Phase 5: Summary ---"
echo "==================================================="
echo "  Snowflake ODBC Flatpak Configuration Complete"
echo "==================================================="
echo
echo "  - System Driver Found at:     $SOURCE_ROOT_PATH"
echo "  - Copied for Flatpak to:      $FLATPAK_DEST_PATH"
echo "  - Registered Flatpak Driver:  '$FLATPAK_DRIVER_SECTION' in $ODBC_INST_FILE"
echo "  - System Linker Updated for:  $FLATPAK_LIB_DIR"
echo
echo "  Navicat (Flatpak) should now be able to use the '$FLATPAK_DRIVER_SECTION' driver."
echo "==================================================="
echo
