#!/bin/bash

mem=768
hdd_size='2G'

#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

usage()
{
  echo "Usage:"
  echo "  $0 create <name>"
  echo "  $0 install <name>"
  echo "  $0 start <name>"
  echo "  $0 status <name>|all"
  echo "  $0 delete <name>"
  exit 1
}

#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

if [ $# -ne 2 ]; then
  usage
fi

operation=$1
vname=$2

if [ -z $operation ]; then
  usage
fi
if [ -z $vname ]; then
  usage
fi

img_dir='/home/pforty/vmachines'
img_name="$img_dir/$vname.img"
log_name="$img_dir/$vname.log"
iso_dir='/home/pforty/iso'
iso_name="$iso_dir/install-x86-minimal-20150414.iso"
timestamp=$(date "+%Y%m%d_%H%M%S")
#=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

create_image()
{
  if [ -e $log_name ];then
    echo "Logfile detected - $log_name"
    echo "skipping ..."
    exit 1
  fi
# QEMU pre-setup
  qemu-img create -f qcow2 $img_name $hdd_size
  echo "Create time - $timestamp" >$log_name
  qemu-img info $img_name >>$log_name
}

boot_cd()
{
  qemu-system-i386 -enable-kvm -m $mem -boot d -cdrom $iso_name -hda $img_name \
    -net nic -net user,hostfwd=tcp::5555-:22 \
    -serial telnet:127.0.0.1:4444,server,nowait
#    -nographic \
#    -vnc unix:vnc_test.socket
  echo "Installation time - $timestamp" >>$log_name
}

boot_hdd()
{
  qemu-system-i386 -enable-kvm -m $mem -boot c -hda $img_name \
    -net nic -net user,hostfwd=tcp::5555-:22 \
    -serial telnet:127.0.0.1:4444,server
  echo "Start time - $timestamp" >>$log_name
}

show_status()
{
  if [ "$vname" == "all" ]; then
    for item in $(ls $img_dir/*.img); do
      vname=$(basename $item)
      echo "vmachine - ${vname%%.img}"
    done
    exit 0 
  fi
  cat $log_name
}

delete_hdd()
{
  if [ -e $img_name ]; then rm -f $img_name && echo "  image for $vname"
  else echo "Image does not exists - $img_name"
  fi 
  if [ -e $log_name ]; then rm -f $log_name && echo "  log for $vname"
  else echo "Log does not exists - $log_name"
  fi 
} 

case "$operation" in
'create') echo ">>Create ..."; create_image ;;
'install') echo ">>Install ..."; boot_cd ;;
'start') echo ">>Start ..."; boot_hdd ;;    
'status') echo ">>Status ..."; show_status ;;
'delete') echo ">>Delete ..."; delete_hdd ;;
*) usage ;;
esac

