#!/bin/bash

# Copyright (c) Veeam Software Group GmbH

set -eE -u -o pipefail

SCRIPT_DIR=$(dirname "$(realpath "${BASH_SOURCE[0]}")"); readonly SCRIPT_DIR;
source "$SCRIPT_DIR/lib/verbose.bash"
source "$SCRIPT_DIR/lib/error-handle.bash"

: "${VCTL_SETUP_TOOL_PATH=/opt/veeam/setup-tool/Veeam.Backup.Setup.Linux.dll}"
readonly VCTL_SETUP_TOOL_PATH
[[ -f $VCTL_SETUP_TOOL_PATH ]] || die "$VCTL_SETUP_TOOL_PATH: not found"

if [[ -z ${VCTL_SETUP_TOOL_ROLE:-} ]]; then
    if [[ -f "$SCRIPT_DIR/vbrctl" ]]; then
        VCTL_SETUP_TOOL_ROLE=vbr
    elif [[ -f "$SCRIPT_DIR/vbemctl" ]]; then
        VCTL_SETUP_TOOL_ROLE=vbem
    else
        die "failed to detect role for setup tool"
    fi
fi
readonly VCTL_SETUP_TOOL_ROLE

declare -A CMD_REMAP=()
case "$VCTL_SETUP_TOOL_ROLE" in
    vbr)
        CMD_REMAP[postgresconfigurator]=backuppostgresconfigurator
        CMD_REMAP[servicesprovider]=backupservicesprovider
    ;;
    vbem)
        CMD_REMAP[postgresconfigurator]=enterprisepostgresconfigurator
        CMD_REMAP[servicesprovider]=enterpriseservicesprovider
    ;;
    *) die "$VCTL_SETUP_TOOL_ROLE: unknown role" ;;
esac

declare -a args=()
if (( $# > 0 )); then
    cmd=${CMD_REMAP[$1]:-$1}
    case "$cmd" in
        backupservicesprovider|enterpriseservicesprovider)
            verbose-disable
        ;;
    esac
    args+=("$cmd")
    shift
    for a in "$@"; do case $a in
        # skip empty values
        ""|sqlserverlogin:|sqlserverport:|entraidsqlserverlogin:|entraidsqlserverport:\
          |componentsautoupgrade:|enablelicenseautoupdate:|databasedeploymode:)
            continue
        ;;
        *) args+=("$a") ;;
    esac; done
fi

umask 0002
verbose-cmd dotnet "$VCTL_SETUP_TOOL_PATH" "${args[@]}"
