#!/bin/bash
set -e

# Pull the list from the Environment Variable (set in Komodo)
# Example: APP_REGISTRY="forgejo guacamole grafana"
echo "Starting Database and User Provisioning for: ${APP_REGISTRY}"

M_ROOT_PASS="${MARIADB_ROOT_PASSWORD}"

for APP in ${APP_REGISTRY}; do
    echo "Processing slot: ${APP}"
    
    # Dynamically find the password variable (e.g., FORGEJO_DB_PASS)
    # This converts "forgejo" to "FORGEJO_DB_PASS"
    UPPER_APP=$(echo "${APP}" | tr '[:lower:]' '[:upper:]')
    PASS_VAR_NAME="${UPPER_APP}_DB_PASS"
    APP_PASS="${!PASS_VAR_NAME}"

    if [ -z "$APP_PASS" ]; then
        echo "ERROR: Variable ${PASS_VAR_NAME} is empty. Skipping ${APP}."
        continue
    fi

    echo "Creating DB and User for ${APP}..."
    mariadb -u root -p"${M_ROOT_PASS}" <<-EOSQL
        CREATE DATABASE IF NOT EXISTS \`${APP}\`;
        CREATE USER IF NOT EXISTS '${APP}'@'%' IDENTIFIED BY '${APP_PASS}';
        GRANT ALL PRIVILEGES ON \`${APP}\`.* TO '${APP}'@'%';
EOSQL
done

echo "All slots provisioned. Flushing privileges..."
mariadb -u root -p"${M_ROOT_PASS}" -e "FLUSH PRIVILEGES;"

echo "Creating Replication User..."
mariadb -u root -p"${MARIADB_ROOT_PASSWORD}" <<-EOSQL
    -- Create the replicator user allowing access from anywhere (or specify IPs)
    CREATE USER IF NOT EXISTS '${REPL_USER}'@'%' IDENTIFIED BY '${REPL_PASSWORD}';
    GRANT REPLICATION SLAVE ON *.* TO '${REPL_USER}'@'%';
    FLUSH PRIVILEGES;
EOSQL