#!/usr/bin/env sh
# shellcheck disable=SC1091
#
# Copyright (C) 2024, Advens <contact@vultureproject.org>
# All rights reserved.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published
# by the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <https://www.gnu.org/licenses/>.

PATH=${PATH}:/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
SCRIPTS_ROOT=/usr/local/share/vulture-utils/

. /usr/local/share/vulture-utils/common.sh

## version
: "${UTILS_VERSION:=$(cat /usr/local/share/vulture-utils/VERSION)}" "${UTILS_VERSION:=unknown}"

usage() {
    cat << EOF
vlt-admin is a CLI tool to run administration/management commands on the system.

Usage:
  vlt-admin <command> [args]

Available Commands:
	upgrade-os	Upgrade the system.
	upgrade-pkg	Upgrade the packages.
	snapshot	Create and manage machine ZFS snapshots.
	restore		Use Snapshots to rollback all or parts of the machine.
	connect		Connect to mongodb and redis easily.

Use "vlt-admin -v" for version information.
Use "vlt-admin <command> -h" for more information about a command.

EOF
    exit 1
}

[ $# -lt 1 ] && usage

CMD=$1
shift

case "${CMD}" in
    version|-v|--version)
        info "${UTILS_VERSION}"
        exit 0
        ;;
    help|-h|--help)
        usage
        ;;
    snapshot|restore)
        # Default to printing help if no argument is given
        if [ $# -eq 0 ]; then
            PARAMS='-h'
        fi
        ;;
    upgrade-os|upgrade-pkg)
        # Nothing to do specificaly for there commands (apart from launching them)
        ;;
    connect)
        # Default to printing help if no argument is given
        if [ $# -eq 0 ]; then
            PARAMS='-h'
        fi
        ;;
    *) # Print usage if sub-command is unknown
        error "unknown command ${CMD}"
        usage
        ;;
esac

SCRIPT_PATH="${SCRIPTS_ROOT}${CMD}.sh"
if [ -f "${SCRIPT_PATH}" ]; then
    : "${UMASK:=022}"
    umask "${UMASK}"

    : "${SH:=sh}"

    if [ -n "${PARAMS}" ]; then
        exec "${SH}" "${SCRIPT_PATH}" "${PARAMS}"
    else
        exec "${SH}" "${SCRIPT_PATH}" "$@"
    fi
else
    error_and_exit "${SCRIPT_PATH} not found."
fi
