#!/bin/bash

cd "$(dirname "${BASH_SOURCE[0]}")" || exit

echo "DB HOST => $DSQL_DB_HOST"

## ==========================
# Wait for Mariadb Server to load
## ==========================
check_mariadb() {
    mysqladmin ping -h"$DSQL_DB_HOST" -u"root" -p"$DSQL_MARIADB_ROOT_PASSWORD" --silent
}

echo "Waiting for MariaDB to be ready..."

until check_mariadb; do
    sleep 2
done

echo "MariaDB is ready!"

## ==========================
# Load Env File
## ==========================
env_file="${1:-.env}"

if [ -f $env_file ]; then
    source $env_file
else
    echo ".env file not found! Please provide a .env file path or add said file to the working direcotry to continue."
    exit 1
fi

## ==========================
# initialise variables
## ==========================

## ==========================
# Setup first root function
## ==========================
query_db_with_main_root() {
    local query="$1"
    local result=$(mariadb -u root -h $DSQL_DB_HOST -p$DSQL_MARIADB_ROOT_PASSWORD -e "$query")

    if [[ $? -ne 0 ]]; then
        echo "Error executing the query."
        return 2
    fi

    local row_count=$(echo "$result" | wc -l)
    if ((row_count > 1)); then
        return 0
    else
        return 1
    fi
}

## ==========================
# Mariadb Query Function
## ==========================
query_db() {
    local query="$1"
    local result=$(mariadb -u root -h $DSQL_DB_HOST -p$DSQL_DB_PASSWORD -e "$query")

    if [[ $? -ne 0 ]]; then
        echo "Error executing the query."
        return 2
    fi

    local row_count=$(echo "$result" | wc -l)
    if ((row_count > 1)); then
        return 0
    else
        return 1
    fi
}

# SQL=$(sed "s/\${\([^}]*\)}/\${\1}/g" "test.sql" | envsubst)

# query_db "$SQL"

## ==========================
# Check for required ENV Variables
## ==========================
if [ -z "${DSQL_DB_TARGET_IP_ADDRESS}" ]; then
    echo "DSQL_DB_TARGET_IP_ADDRESS env is not set"
    exit 1
fi

if [ -z "${DSQL_DB_PASSWORD}" ]; then
    echo "DSQL_DB_PASSWORD env is not set"
    exit 1
fi

if [ -z "${DSQL_DB_READ_ONLY_PASSWORD}" ]; then
    echo "DSQL_DB_READ_ONLY_PASSWORD env is not set"
    exit 1
fi

if [ -z "${DSQL_DB_FULL_ACCESS_PASSWORD}" ]; then
    echo "DSQL_DB_FULL_ACCESS_PASSWORD env is not set"
    exit 1
fi

## ==========================
# Create Datasquirel Root User
## ==========================

echo "HOST ENV: $DSQL_HOST_ENV"

if [ -n "${NEXT_PUBLIC_DSQL_LOCAL}" ]; then
    if [[ "$DSQL_HOST_ENV" == *"dev_dev"* ]]; then
        echo "Dev Environment. Root user setup not required"
    else
        query_db_with_main_root "select user,host from mysql.user where user='root' and host='$DSQL_DB_TARGET_IP_ADDRESS';"

        if [[ $? == 0 ]]; then
            echo "Root User Exists"
        else
            echo "No Root User. Creating ..."
            query_db_with_main_root "CREATE USER IF NOT EXISTS 'root'@'$DSQL_DB_TARGET_IP_ADDRESS' IDENTIFIED BY '$DSQL_DB_PASSWORD';\
                GRANT ALL PRIVILEGES ON *.* TO 'root'@'$DSQL_DB_TARGET_IP_ADDRESS' WITH GRANT OPTION;\
                FLUSH PRIVILEGES;"

            query_db "select user,host from mysql.user where user='root' and host='$DSQL_DB_TARGET_IP_ADDRESS';"

            if [ $? -ne 0 ]; then
                echo "Error: Couldn't create root user."
                exit 1
            else
                query_db "drop user 'root'@'%';"
            fi
        fi
    fi
else
    echo "Production Environment. Root user setup not required"
fi

## ==========================
# Create Datasquirel Database
## ==========================
check_database_exists=$(query_db "show databases like 'datasquirel';")

if [[ $? == 0 ]]; then
    echo "Dsql Database exists"
else
    echo "Dsql Database does not exist. Creating ..."
    query_db "create database datasquirel;"
fi

## ==========================
# Create Datasquirel Read Only User
## ==========================
query_db "select user,host from mysql.user where user = '$DSQL_DB_READ_ONLY_USERNAME' and host = '$DSQL_DB_TARGET_IP_ADDRESS';"

if [[ $? == 0 ]]; then
    echo "$DSQL_DB_READ_ONLY_USERNAME User Exists"
else
    echo "No $DSQL_DB_READ_ONLY_USERNAME User. Creating ..."
    query_db "CREATE USER IF NOT EXISTS '$DSQL_DB_READ_ONLY_USERNAME'@'$DSQL_DB_TARGET_IP_ADDRESS' IDENTIFIED BY '$DSQL_DB_READ_ONLY_PASSWORD';"
fi

## ==========================
# Create Datasquirel Full Access User
## ==========================
DSQL_DB_FULL_ACCESS_USERNAME="datasquirel_full_access"
query_db "select user,host from mysql.user where user = '$DSQL_DB_FULL_ACCESS_USERNAME' and host = '$DSQL_DB_TARGET_IP_ADDRESS';"

if [[ $? == 0 ]]; then
    echo "$DSQL_DB_FULL_ACCESS_USERNAME User Exists"
else
    echo "No $DSQL_DB_FULL_ACCESS_USERNAME User. Creating ..."
    query_db "CREATE USER IF NOT EXISTS '$DSQL_DB_FULL_ACCESS_USERNAME'@'$DSQL_DB_TARGET_IP_ADDRESS' IDENTIFIED BY '$DSQL_DB_FULL_ACCESS_PASSWORD';"
fi

query_db "FLUSH PRIVILEGES;"

exit 0
