#!/bin/bash
# ====================================================================
#
#   Detect a database type
#
# --------------------------------------------------------------------
# ah: <www.axel-hahn.de>
# 2024-02-xx  v0.1  ah   Initial version
# --------------------------------------------------------------------

cd $( dirname $0 ) || exit 1

. vendor/ini.class.sh || exit 1
. vendor/color.class.sh || exit 1

. $(dirname $0)/includes/dbdetect.class.sh || exit 1

DBD_DEBUG=0
showInfos=0
USAGE="Detect profiles for databases which are located in 
$DBD_BASEDIR.

For detected profiles it shows its used parameters.
This script helps you to define / verify custom profiles.

SYNTAX: $( basename $0) [OPTIONS] [FILTER]

OPTIONS:
    -h|--help     Show this help
    -i|--infos    Show infos about detected profiles
    -v|--verbose  Show debug information during detection. This helps to find
                  out why a profile was skipped.

PARAMETERS:
    FILTER   a string / regex to filter profilenames.

SXYNTAX:
    $( basename $0) mysql   Test profiles matching 'mysql' only
    $( basename $0) -v      Test all profiles with debug output
"
# --------------------------------------------------------------------

# ----------------------------------------------------------------------
# MAIN
# ----------------------------------------------------------------------

echo ';' >&2
echo '; --==##|  DATABASE PROFILE DETECTOR  |##==-- '
echo ';' >&2

while [ "$#" -gt 0 ]; do case $1 in
    -h|--help)      echo "$USAGE"; exit 0;;
    -i|--infos)     showInfos=1; shift 1;;
    -v|--verbose)   DBD_DEBUG=1; shift 1;;

    *) if grep "^-" <<< "$1" >/dev/null ; then
        echo; echo "ERROR: Unknown parameter: $1"; echo; echo "$USAGE"; exit 2
       fi
       break;
       ;;
esac; done

sFilter="${1:-.}"
test ! "${sFilter}" = "." && ( echo -n "Filter enabled: "; color.echo "blue" "${sFilter}"; echo ';' >&2)

dbdetect._wd "------"
for config in $(dbdetect.getConfigs | grep "${sFilter}"); do
    dbdetect._wd "----- $config"
    dbdetect.validate $config

    if dbdetect.exists $config; then
        color.print "green" "FOUND"; echo ": $config"
        if [ "$showInfos" -gt "0" ]; then
            echo "  Type       : $( dbdetect.getType    $config )"
            echo "  Target dir : $( dbdetect.getProfile $config )"
            echo "  runas      : $( dbdetect.runas )"
            echo "  Params     : $( dbdetect.getParams )"
            echo "  Env        : $( dbdetect.setenv )"
            echo "  Files      : $( dbdetect.getFiles | grep -c '.' )"
            echo ';'
        fi
    else
        echo "SKIP : $config" 
    fi
    dbdetect._wd
done

# --------------------------------------------------------------------
