#!/bin/sh
#
# Copyright (C) 2017, 2020  Etersoft
# Copyright (C) 2017, 2020  Vitaly Lipatov <lav@etersoft.ru>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

PROGDIR=$(dirname $0)
[ "$PROGDIR" = "." ] && PROGDIR=$(pwd)

# will replaced to /usr/share/evz during install
SHAREDIR=/usr/share/evz

load_helper()
{
    local CMD="$SHAREDIR/$1"
    [ -r "$CMD" ] || { echo "Have no $CMD helper file" >&2 ; exit 1 ; }
    . $CMD
}

load_helper evz-sh-functions
load_helper evz-functions

check_tty

SUPPORTED_ENGINES="vzctl docker qm pct vboxmanage"

MCTL=""
EVZCTL_supported=""
for i in $SUPPORTED_ENGINES ; do
    which $i 2>/dev/null >/dev/null || continue
    [ -n "$MCTL" ] || MCTL="$i"
    [ "$EVZCTL" = "$i" ] && EVZCTL_supported="$EVZCTL" && break
done
[ -n "$EVZCTL_supported" ] && MCTL="$EVZCTL_supported"


# FIXME: override get_help
# print options description from HELPCMD/HELPOPT lines in the code
get_help()
{
    [ -z "$MCTL" ] && warning "Can't detect supported virtualization tool" && return
    grep -v -h -- "^#" $0 $SHAREDIR/evz-$MCTL | grep -- "# $1" | while read n ; do
        opt=$(echo $n | sed -e "s|) # $1:.*||g")
        desc=$(echo $n | sed -e "s|.*) # $1:||g")
        printf "    %-20s %s\n" $opt "$desc"
    done
}

phelp()
{
	echo "$Descr
$Usage
 Commands:
$(get_help HELPCMD)

 Options:
$(get_help HELPOPT)

 Examples:
    # evz start ID ID ID
    # evz list ALL
"
}

print_version()
{
        echo "Etersoft virtualization wrapper version 0.4.3-alt0.M90P.1"
        echo "Copyright (c) Etersoft 2017, 2020"
        echo "This program may be freely redistributed under the terms of the GNU AGPLv3."
}

progname="${0##*/}"

Usage="Usage: $progname [options] [<command>] [params]..."
Descr="evz - virtualization wrapper (supported engines: $SUPPORTED_ENGINES)"

progname="${0##*/}"


force=''
target=''
verbose=--verbose

case "$1" in
    -h|--help|help)       # HELPOPT: this help
        phelp
        exit
        ;;
    -V|--version)         # HELPOPT: print version
        print_version
        exit
        ;;
    -q|--quiet)           # HELPOPT: be silent
        verbose=
        shift
        ;;
    -f|--force)           # HELPOPT: override target
        force=-f
        shift
        ;;
esac

[ -n "$MCTL" ] || fatal "Can't detect supported virtualization tool"

load_helper evz-$MCTL
evz_$MCTL "$@"
