#!/usr/bin/bash
#
# Backup all virtual systems
# Copyright (C) 2013-2024 by Thomas Dreibholz
#
# 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


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

NORNET_DIRECTORY="/etc/nornet"

# Check whether NorNet directory is existing
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

DIRECTORY="$1"
if [ ! -d "$DIRECTORY" ] ; then
   echo >&2 "ERROR: Directory $DIRECTORY does not exist!"
   exit 1
fi

VMs=`sudo -u $NorNet_LocalNode_NorNetUser VBoxManage list vms 2>&1 | grep "^\"" | sed -e "s/ {.*}$//g" -e "s/^\"//g" -e "s/\"$//g"`
for vm in $VMs ; do
   echo -e "\n\x1b[34m`date +%FT%H:%M:%S`: ====== Backup for virtual system ${vm} ... ======\x1b[0m\n"

   if [ -e "$DIRECTORY/${vm}.ova" ] ; then
      mv "$DIRECTORY/${vm}.ova" "$DIRECTORY/${vm}.ova~"
   fi
   Backup-VSystem "${vm}" "$DIRECTORY/${vm}.ova" || true
done
