#!/usr/bin/sh -e
#
# Show all virtual systems
# Copyright (C) 2013-2024 by Thomas Dreibholz
# Copyright (C) 2014 by Forough Golkar <forough.golkar87@gmail.com>
# Copyright (C) 2013 by Nima Fallah Darya <nima.darya@gmail.com>
#
# 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, 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 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 <http://www.gnu.org/licenses/>.
#
# Contact: dreibh@simula.no


# ###### Call VBoxManage with timeouts #######################################
vmcontrol ()
{
   intTimeout=15
   killTimeout=30
   sudo -u $NorNet_LocalNode_NorNetUser timeout -s INT -k $killTimeout $intTimeout VBoxManage controlvm $@ || true
}



# ###### Main program #######################################################
if [ $# -lt 1 ] ; then
   echo >&2 "Usage: $0 VM_name"
   exit 1
fi

NORNET_DIRECTORY="/etc/nornet"
MACHINE_NAME="$1"

# ====== Get NorNet user name ===============================================
if [ -e $NORNET_DIRECTORY/nornetapi-config ] ; then
   . $NORNET_DIRECTORY/nornetapi-config
elif [ -e ./nornetapi-config ] ; then
   . ./nornetapi-config
fi
if [ "$NorNet_LocalNode_NorNetUser" = "" ] ; then
   NorNet_LocalNode_NorNetUser="nornetpp"
fi


# ====== Reset the machine ==================================================
if [ "$NorNet_Server_VirtualizationSystem" = "" -o "$NorNet_Server_VirtualizationSystem" = "VirtualBox" ] ; then
   vmcontrol "$MACHINE_NAME" reset

elif [ "$NorNet_Server_VirtualizationSystem" = "KVM" ] ; then
   virsh reset "$MACHINE_NAME"

else
   echo >&2 "ERROR: Bad setting $NorNet_Server_VirtualizationSystem for NorNet_Server_VirtualizationSystem!"
   exit 1
fi
