#!/bin/bash

usage()
{
  echo
  echo "Usage: $PROG_NAME -n -s"
  echo
  echo " -n      =   Name of the VM to start."
  echo " -s      =   y/n. Check and start or not depending the previous state. If y and $VM_STATE=running then start."
  echo
  exit 0
}

function get_vm_state()
{ 
  echo "$PROG_NAME: Querying VM State..."
  VM_STATE="$(virsh dominfo "$VM_NAME" | grep -w "State:" | awk '{print $2}')"
}

set_variable()
{
  local varname=$1
  shift
  if [ -z "${!varname}" ]; then
    eval "$varname=\"$@\""
  else
    echo "Error: $varname already set"
    usage
  fi
}

####################################################################
# Main script starts here

set_variable PROG_NAME "$(basename "$0")"
set_variable CHECK_FILE "/tmp/VM_PREV_STATE"

if [[ $1 == "" ]]; then
    usage;
    exit;
else
    while getopts 'n:s:?h' c
    do
    case $c in
        n) set_variable VM_NAME "$OPTARG" ;;
        s) set_variable CHK_PREV_STATE "$OPTARG" ;;
        h|?) usage ;; esac
    done
fi

# ---------------
# Error Handling
# ---------------
# set -e
# trap 'catch $? $LINENO' EXIT

# catch() {
  # echo "catching!"
  # if [ "$1" != "0" ]; then
    # # error handling goes here
    # echo "$PROG_NAME: Error $1 occurred on $2"
  # fi
# }


# if [ -f "$CHECK_FILE" ] 
# then
#   read -r line<"$CHECK_FILE"
#   if [ "$line" != "running" ] 
#   then
#     rm "$CHECK_FILE" # The vm was not runnin when stopped. Not starting it...
#   exit 0
#   fi
# fi

# rm "$CHECK_FILE"

# ------------------
# VM Already Running
# ------------------
get_vm_state "$VM_NAME"
# echo "$VM_STATE"
if [ "$VM_PREV_STATE" == "running" ]
then
  echo "$PROG_NAME: $VM_NAME already running" >&2
  exit 0
else
  virsh start "$VM_NAME"
  get_vm_state "$VM_NAME"
  if [ "$VM_STATE" == "running" ]
  then
    echo "$PROG_NAME: $VM_NAME successfully statrted" >&2
    exit 0
  else
    echo "$PROG_NAME: Error $VM_NAME could not be statrted" >&2
    exit 1
  fi
fi
