#!/bin/sh
#
# Copyright (C) 2017  Etersoft
# Copyright (C) 2017  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

check_tty

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 vzctl wrapper version 0.1.1-alt0.M80P.1"
        echo "Copyright (c) Etersoft 2017"
        echo "This program may be freely redistributed under the terms of the GNU AGPLv3."
}

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

Usage="Usage: $progname [options] [<command>] [params]..."
Descr="evz - vzctl wrapper"

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

line_filter()
{
    # https://stackoverflow.com/questions/1251999/how-can-i-replace-a-newline-n-using-sed
    sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g' -e "s| \+| |g" -e "s|^ ||g" -e "s| $||g"
}

list_all()
{
    vzlist -1 "$@" | line_filter
}

list_ALL()
{
    vzlist -1 -a "$@" | line_filter
}

get_list()
{
    if [ "$1" = "ALL" ] ; then
        list_ALL
        return
    fi
    if [ "$1" = "all" ] ; then
        list_all
        return
    fi
    if [ -n "$1" ] ; then
        list_ALL "$@"
        return
    fi
    list_all
}

# TODO: add all support for all cases

CMD=$1
shift
case $CMD in
    off)                             # HELPCMD: stop container(s) and disable start on boot
	LIST=$(get_list "$@")
	for i in $LIST ; do
	    info "Stopping $i ..."
	    vzctl stop $i
	    # TODO: check if enabled
	    vzctl set $i --onboot no --save
	done
	;;
    on)                              # HELPCMD: enable start on boot and start container(s)
	for i in "$@" ; do
	    info "Starting $i ..."
	    # TODO: check if enabled
	    vzctl set $i --onboot yes --save
	    vzctl start $i
	done
	;;
    status)                          # HELPCMD: print container(s) status
	LIST=$(get_list "$@")
	info "Do $CMD for $LIST ..."
	for i in $LIST ; do
	    vzctl $CMD $i
	done
	;;
    compact)                         # HELPCMD: do named operation on container(s)
	LIST=$(get_list "$@")
	for i in $LIST ; do
	    info "Do $CMD on $i ..."
	    vzctl $CMD $i
	done
	;;
    stop)                            # HELPCMD: stop container(s)
	LIST=$(get_list "$@")
	for i in "$@" ; do
	    info "Stopping $i ..."
	    vzctl stop $i
	done
	;;
    start)                           # HELPCMD: start container(s)
	LIST=$(get_list "$@")
	for i in $LIST ; do
	    info "Starting $i ..."
	    vzctl start $i
	done
	;;
    list)                            # HELPCMD: list avaiable container(s) (use -q|-1 for list only ID, list ALL|-a for list ever stopped containers)
	# if -q, just id list
	if [ -z "$verbose" ] || [ "$1" = "-1" ] || [ "$1" = "-q" ] ; then
		[ -z "$verbose" ] || shift
		get_list "$@"
		exit
	fi
	vzlist "$@"
	;;
    exec)                            # HELPCMD: execute command by list (all for all containers)
    	INCMD="$1"
    	shift
	LIST=$(get_list "$@")
	for i in $LIST ; do
	    #info "Executing on $i ..."
	    #printf "%3d: %s" $i "$(vzctl exec $i "$INCMD")"
	    #vzctl exec $i "$INCMD" | sed -e "s|^|$(printf "%3d: " $i)|g"
	    vzctl exec $i "$INCMD"
	done
	;;
    info)                            # HELPCMD: print containers(s) info (vzlist like)
	LIST=$(get_list "$@")
	#for i in $LIST ; do
	    #info "Executing on $i ..."
	    #printf "%3d: %s" $i "$(vzctl exec $i "$INCMD")"
	    #vzctl exec $i "$INCMD" | sed -e "s|^|$(printf "%3d: " $i)|g"
	    #vzctl exec $i "$INCMD"
	    # TODO: internal IP, red if internal hostname differs
	    vzlist $LIST -o ctid,ip,hostname,diskspace
	#done
	;;
    destroy)                         # HELPCMD: destroy container(s) by list
        echo "You request to destroy follow containers:"
        vzlist -a "$@"
        #local response
        read -r -p "Are you sure? [Yes/No]" response
        [ "$response" = "Yes" ] || fatal "Have no receive your accept."

	for i in "$@" ; do
	    info "Stopping $i ..."
	    vzctl stop $i
	    vzctl destroy $i
	done
	;;
    *)
	fatal "Unknow command '$CMD'. Use --help to get help."
	;;
esac
