#!/bin/zsh

# Version: 1.0.0
# Date: 2023-10-12
# Authors: Christian Muck, Patrik Burzynski, Wilfrid Utz
# Installation scripts: MIT License, (C) Copyright 2023 OMiLAB

# Creates and initializes the database file.

# This script uses set_variables.sh to set various variables that are used.
# The relevant variables are:
# force_operation - Performs the operation independent of checks / user inputs.
# wine_prefix_dir - The Wine prefix directory.
# tool_installation_dir - The directory to install the tool to inside the Wine
#   prefix.
# license_key - The license key to use. If it is empty, then it tries to load
#   the license information from the tools installation directory.
# database_name - The name of the database, which is also the name of the file.

# Notes about some specifics of the script/s:
# * ${0:a:h} - The absolute path to the directory where THIS script is located.
# * ${@} - represents all the parameters / arguments that have been passed to
#   this script.
# * Calling a script via "./filename.sh" executes them in a separate process
#   (at least in zsh), so they should have their own local (environment)
#   variables.
# * Adding a script via the source commands behaves as if the code from the
#   other script was part of this script, similar to #include in C/C++.



# Process passed arguments and load various relevant varaiables and functions.
source "${0:a:h}/common_script.sh"

# Helper variables.
local full_tool_installation_dir="${wine_prefix_dir}/drive_c/${tool_installation_dir}"



# Check if the database already exist.
# The logic has to follow the same logic that is used by ADOxx.
# The first test is SIMPLE, assuming that the file is in a very specific
# location. This SHOULD be the most likely case.
local create_database=1
local user_folder="$(id -un)"
local database_file="${wine_prefix_dir}/drive_c/users/${user_folder}/AppData/Roaming/ADOxx/sqlitedbs/${database_name}.sqlite3"
[ -f "${database_file}" ]
local database_exists=$?
if [ ${database_exists} -eq 0 ]
then
    echo "Database already exists: ${database_file}"
fi

# If the previous check did not find the database file, then we "ask" Wine
# instead. There are cases where the file can be located in a different place:
# * Some Wine versions use "Application Data/" instead "AppData/Roaming/".
# * Some Wine versions do not use the system user's name for the user name
#   in the Wine prefix.
if [ ${database_exists} -ne 0 ]
then
    # First check if Wine is installed and the Wine prefix folder exists.
    command -v wine &>/dev/null
    if [ $? -ne 0 ]
    then
        echo ${error_style}"Wine not available. Unable to create the database."
        echo "Please install Wine first and ensure that the wine command is avilable."${default_style}
        return 1
    fi
    if [ ! -d "${wine_prefix_dir}" ]
    then
        echo ${error_style}"Wine prefix not available. Unable to create the database."
        echo "Please ensure that the Wine prefix is available: ${wine_prefix_dir}."${default_style}
        return 1
    fi
    # We get the value of the %APPDATA% environment variable.
    local wine_prefix_addpata_dir="$(LANG=en_US WINEARCH=win64 WINEPREFIX=${wine_prefix_dir} WINEDEBUG=-all wine cmd /c "ECHO %APPDATA%" 2>/dev/null)"
    # And then we use winepath.exe to transform it to a unix path.
    local wine_prefix_appdata_dir="$(LANG=en_US WINEARCH=win64 WINEPREFIX=${wine_prefix_dir} WINEDEBUG=-all wine winepath.exe "${wine_prefix_addpata_dir::-1}" 2>/dev/null)"
    local database_file="${wine_prefix_appdata_dir}/ADOxx/sqlitedbs/${database_name}.sqlite3"
    # Check again fi the database file exists.
    [ -f "${database_file}" ]
    local database_exists=$?
    if [ ${database_exists} -eq 0 ]
    then
        echo "Database already exists: ${database_file}"
    fi

    # Approaches previously tried:

    # Using compgen to use all the user in the Wine prefix.
    # This also used an amount_of_database_files_found variable and a lot of
    # other code later on.
    #wineprefix_users_folder="${wine_prefix_dir}/drive_c/users"
    #database_file_in_user_folder="AppData/Roaming/ADOxx/sqlitedbs/${database_name}.sqlite3"
    #found_database_files="$(compgen -G "${wineprefix_users_folder}/*/${database_file_in_user_folder}" 2>/dev/null)"

    # Using find to search for the database file in the Wine prefix folder.
    # This also used an amount_of_database_files_found variable and a lot of
    # other code later on.
    #database_file_name="${database_name}.sqlite3"
    #wineprefix_users_folder="${wine_prefix_dir}/drive_c/users"
    #found_database_files="$(find "${wineprefix_users_folder}" -name "${database_file_name}" 2>/dev/null)"
fi

# If we still didn't find the database file then we assume it is missing.
if [ ${database_exists} -ne 0 ]
then
    echo "Database missing."
    local create_database=0
fi



# If the database already exists, then prompt the user on how to proceed.
if [ ${database_exists} -eq 0 ]
then
    echo ${warning_style}"Deleting the database file will also delete all models of the tool."${default_style}
    echo ${warning_style}"Make sure you no longer need them or that they have been exported as"${default_style}
    echo ${warning_style}".adl / .xml files first."${default_style}
    echo "Database file to delete: ${database_file}"
    prompt_user_default_no ${input_style}"Should the database be deleted? [y/N] or press CTRL-C to abort."${default_style}
    if [ $? -eq 0 ]
    then
        echo "Deleting database."
        rm -f "${database_file}"
        local create_database=0
    fi
fi



# Check if example models to be imported exist.
local sample_models_location="${full_tool_installation_dir}/adostd.adl"
[ -f "${sample_models_location}" ]
local example_models_available=$?
if [ ${example_models_available} -eq 0 ]
then
    echo "Found example models."
fi



# Create and initialize the database.
if [ ${create_database} -eq 0 ] || [ ${force_operation} -eq 0 ]
then
    # If license_key is missing, then read it from the license file in the
    # ADOxx installation folder.
    if [ "${license_key}" = "" ]
    then
        echo "Loading license key."
        local license_key="$(<"${full_tool_installation_dir}/alicdat.ini")"
    fi

    # If we can't load the license key then abort.
    if [ "${license_key}" = "" ]
    then
        echo ${error_style}"FAILED to determine license key."
        echo "Please configure database manually."${default_style}
        return 1
    fi

    echo "Creating and initializing database (${database_name})."
    echo ${input_style}"Confirm the success message once it's done (might hide behind some windows)."${default_style}
    if [ ${example_models_available} -eq 0 ]
    then
        LANG=en_US WINEARCH=win64 WINEPREFIX=${wine_prefix_dir} WINEDEBUG=-all wine "C:/${tool_installation_dir}/adbinst.exe" "-d${database_name}" "-l${license_key}" -sSQLITE -iNO_SSO -lang2057 -c+ "-sample${sample_models_location}"
    else
        LANG=en_US WINEARCH=win64 WINEPREFIX=${wine_prefix_dir} WINEDEBUG=-all wine "C:/${tool_installation_dir}/adbinst.exe" "-d${database_name}" "-l${license_key}" -sSQLITE -iNO_SSO -lang2057 -c+
    fi

    # Note: Later logic relies on NOT changing the value of the create_database variable here!
fi



# Check if the database files exist and "return" 0 (true) or 1 (false).
if [ ${create_database} -eq 0 ] && [ ! -f "${database_file}" ]
then
    echo ${error_style}"FAILED creating database."
    echo "Please create and configure database manually."${default_style}
    return 1
else
    return 0
fi
