#!/usr/bin/bash
#
# Check status of virtual system
# 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

# Bash options:
set -e


# ###### Call VBoxManage with timeouts #######################################
vminfo ()
{
   intTimeout=30
   killTimeout=35
   sudo -u $NorNet_LocalNode_NorNetUser env HOME=~$NorNet_LocalNode_NorNetUser timeout -s INT -k $killTimeout $intTimeout VBoxManage showvminfo $@ || true
}


# ###### Main program #######################################################
if [ $# -ne 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


# ====== Obtain machine status ==============================================
status="BAD_MACHINE"

if [ "$NorNet_Server_VirtualizationSystem" = "" -o "$NorNet_Server_VirtualizationSystem" = "VirtualBox" ] ; then
   s=`vminfo "$MACHINE_NAME" --machinereadable | grep VMState=` && \
   status=`echo $s | sed -e "s/VMState=//" -e "s/\"//g"` || true

elif [ "$NorNet_Server_VirtualizationSystem" = "KVM" ] ; then
    status=`env LANG=C HOME=~$NorNet_LocalNode_NorNetUser virsh dominfo "$MACHINE_NAME" | grep "^State:" | sed -e "s/State://" -e "s/^ *//g" -e "s/ *$//g" || true`
    if [ "$status" = "shut off" ] ; then
       status="poweroff"
    fi

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

echo "$status"
