#!/bin/bash

set -o errexit
set -o nounset
set -o pipefail
#set -o xtrace

zkk_vg="vgoldiscsi"
zkk_standard_lv_opts=""
zkk_vm_prefix="vm_"
##zkk_install_source="http://ftp.tugraz.at/mirror/centos/7/os/x86_64/"
##zkk_ks_file_path="http://installer/kickstart/kickstart-centos7-new.cfg"
zkk_install_source="http://ftp.tugraz.at/mirror/centos/8/BaseOS/x86_64/os/"
zkk_ks_file_path="http://installer2020/kickstart/centos8.ks"
zkk_vm_primary_bridge="brzkk"

## check parameters
if [ $# -lt 1 ] || [ $# -gt 3 ]; then
  echo "  usage: $0 <hostname> [memory [cpus]]"
  echo "example: $0 purple 2048 2"
  exit 10
elif [ $# -gt 1 ] && ! [[ "$2" =~ ^[0-9]+$ ]] ; then
  echo "size must be a number!"
  exit 10
elif [ $# -gt 2 ] && ! [[ "$3" =~ ^[0-9]+$ ]] ; then
  echo "cpus must be a number!"
  exit 10
fi

## declare some variables
x_host=$1
x_mac=$(curl -s ftp://installer/ZKK/ethers.zkk |grep [[:space:]]${x_host}[[:space:]]*$ | awk '{print $1}')
if ! [[ "$x_mac" =~ ^[0-9a-f:]+$ ]] ; then
  echo "No Mac-Address found!"
  exit 20
fi

# "use zkk_vg"
# "use zkk_install_source"
# "use zkk_ks_file_path"
x_cpus=2
x_size=4096
if [ $# -gt 1 ] ; then x_size=$2 ; fi
if [ $# -gt 2 ] ; then x_cpus=$3 ; fi

## safety question
echo "This will install the machine ”${x_host}” from scratch!"
read -r -p "Are you sure? [yes/no] " response
case ${response} in
    [yY][eE][sS])
        echo
        ;;
    *)
        exit
        ;;
esac

## get VM disks
vm_disks=""
rootok=false
disks=$(lvs -o lv_name ${zkk_vg} | grep "^[[:space:]]*${zkk_vm_prefix}${x_host}\." |sed s/[[:space:]]*${zkk_vm_prefix}${x_host}\.// )
for disk in ${disks} ; do
  if [ ${disk} = "root" ] ; then rootok=true ; fi
  if [ ${disk} = "root_enc" ] ; then rootok=true ; fi
  if [[ "${disk}" =~ _enc$ ]] ; then
    vm_disks="${vm_disks} --disk path=/dev/mapper/dec-${zkk_vg}-${zkk_vm_prefix}${x_host}.${disk%_*},bus=scsi,serial=${disk%_*}"
  else
    vm_disks="${vm_disks} --disk path=/dev/${zkk_vg}/${zkk_vm_prefix}${x_host}.${disk},bus=scsi,serial=${disk}"
  fi
done

if ! ${rootok} ; then echo "Abort creating "${x_host}". root Partition missing!"; exit 9 ; fi

## remove running VM
virsh destroy ${x_host} || true
virsh undefine ${x_host} || true

## do the install
virt-install -n ${x_host} -r ${x_size} --vcpus=${x_cpus} -l ${zkk_install_source} \
--extra-args="inst.sshd inst.geoloc=0 inst.loglevel=debug ks=${zkk_ks_file_path}" \
${vm_disks} --network bridge=${zkk_vm_primary_bridge},model=virtio,mac=${x_mac} &

sleep 10

zkk-vnc-virsh-host ${x_host}
