#!/bin/bash

#############################################################################
# Database Paths and Socket Mapping
# Derives platform-specific database locations based on detected system info
# Must be sourced AFTER lib/system-detect.sh has set SYS_* variables
#############################################################################

# Source guard
if [ -n "${_DATABASE_PATHS_LOADED:-}" ]; then
    return 0
fi
readonly _DATABASE_PATHS_LOADED=1

#############################################################################
# MYSQL/MARIADB PATHS
#############################################################################

derive_mysql_paths() {
    case "$SYS_OS_TYPE" in
        ubuntu|debian)
            # Ubuntu/Debian standard locations
            export SYS_DB_SOCKET="/var/run/mysqld/mysqld.sock"
            export SYS_DB_CONFIG="/etc/mysql/my.cnf"
            export SYS_DB_CONFIG_DIR="/etc/mysql/conf.d"
            export SYS_DB_DATA_DIR="/var/lib/mysql"
            export SYS_DB_BINARY="/usr/sbin/mysqld"
            ;;
        *)
            # RHEL/CentOS/AlmaLinux standard locations
            export SYS_DB_SOCKET="/var/lib/mysql/mysql.sock"
            export SYS_DB_CONFIG="/etc/my.cnf"
            export SYS_DB_CONFIG_DIR="/etc/my.cnf.d"
            export SYS_DB_DATA_DIR="/var/lib/mysql"
            export SYS_DB_BINARY="/usr/sbin/mysqld"
            ;;
    esac

    # Common paths for both
    export SYS_DB_TMPDIR="/tmp"
    export SYS_DB_PID_FILE="/var/run/mysqld/mysqld.pid"
}

#############################################################################
# POSTGRESQL PATHS
#############################################################################

derive_postgresql_paths() {
    case "$SYS_OS_TYPE" in
        ubuntu|debian)
            export SYS_PG_SOCKET="/var/run/postgresql"
            export SYS_PG_CONFIG="/etc/postgresql"
            export SYS_PG_DATA_DIR="/var/lib/postgresql"
            export SYS_PG_BINARY="/usr/lib/postgresql/bin/postgres"
            ;;
        *)
            # RHEL/CentOS standard locations
            export SYS_PG_SOCKET="/var/run/postgresql"
            export SYS_PG_CONFIG="/var/lib/pgsql/data"
            export SYS_PG_DATA_DIR="/var/lib/pgsql"
            export SYS_PG_BINARY="/usr/bin/postgres"
            ;;
    esac
}

#############################################################################
# MAIN DERIVATION FUNCTION
#############################################################################

derive_all_database_paths() {
    case "$SYS_DB_TYPE" in
        mysql|mariadb)
            derive_mysql_paths
            ;;
        postgresql)
            derive_postgresql_paths
            ;;
    esac
}

# Auto-run if sourced with detection complete
if [ -n "${SYS_DETECTION_COMPLETE:-}" ]; then
    derive_all_database_paths
fi
