#!/bin/bash
#
#######################################################
#
# automate-00-destroyVMs
#
#######################################################
#
# License: GPL
# Author: Fabian Herschel 2016
# (c) 2016-2018 SUSE Linux GmbH, Nuremberg, Germany
#
# To be called at LandscapeMaster
#
# Tasks automated:
# - destroy already running VMs
# - undefine the VMs
#
# Preequisites:
# - both hypervisors (hana-01 and hana-02 up and running)
# - dhcp on br0 (userlan)
# - nating on br0 (userlan)
# - VMs are *not* already available
#
# Next Automation Script
# automate-01-install-sles
#
#######################################################
#
#    host glishorn01 {
#        hardware ethernet 52:54:00:42:57:2a;
#        fixed-address 192.168.1.81;
#        option host-name "glishorn01";
#    }
#
# Version 3.0.2018.03.21.1
# TODO: PRIO1: ALSO ADD SERVICE IP LABELS!!
#
source /usr/share/Landscape/bin/get_values
export PATH="$PATH:$LandscapeMain/bin"

GROUP="all"
node="all"
declare -a allSystems=()

while [ $# -gt 0 ]; do
    case "$1" in
        --group=* | --owner=* ) GROUP=${1#*=}
                   ;;
        --node=* ) node=${1#*=}
                   ;;
    esac
    shift
done

function filterSystem()
{
    local systemDef="" systemKV=""
    local fields="SYSTEM"
    local f="" ptrF="" outPut=0 outStr=""
    while [ $# -gt 0 ]; do
        case "$1" in
            --system ) systemDef="$2"; shift
                       ;;
            --fields ) fields="$2"; shift
                       ;;
        esac
        shift
    done
    for systemKV in ${systemDef}; do
        sKey="${systemKV%=*}"; sKey=${sKey^^}
        sValue=${systemKV#*=}
        local SYSTEM_$sKey=$sValue
    done
    # BAUSTELLE
    if [ $GROUP = "all" -a $node = "all" ]; then
        outPut=1
    elif [ $GROUP = "$SYSTEM_OWNER" -a $node = "all" ]; then
        outPut=1
    elif [ $GROUP = "all" -a $node = "$SYSTEM_SYSTEM" ]; then
        outPut=1
    elif [ $GROUP = "$SYSTEM_OWNER" -a $node = "$SYSTEM_SYSTEM" ]; then
        outPut=1
    fi
    if [ $outPut -eq 1 ]; then
        for f in $fields; do
            ptrF="SYSTEM_$f"
            outStr="${outStr}${outStr:+ }${!ptrF}"
        done
        printf "%s" "$outStr"
    fi
}

# select hyp,system from LandscapeSystems where ...

for systemDef in "${LandscapeSystems[@]}"
do
    help1=$(filterSystem --fields 'SYSTEM IP HYP' --system "$systemDef"; printf "\n")
    if [ ${#allSystems[@]} -gt 0 ]; then
        allSystems=( "${allSystems[@]}" "$help1" )
    else 
        allSystems=( "$help1" )
    fi
done

#
#####################################
#
#
# pxefile
#
pxeRoot="/srv/tftpboot/pxelinux.cfg"
bootLoader="${LandscapeSLES}/boot/x86_64/loader"


>/tmp/dhcpd.hosts.$$
for s in "${allSystems[@]}"; do
    echo "system: $s"
    read sys ip hyp X <<< "$s"
    #
    # TODO: virsh also for remote hypervisor, if needed
    mac=$(ssh $hyp virsh domiflist  "${sys}" | awk '$3 == lan { print $5}' lan=${LandscapeDefaultSwitch})
    virsh domiflist  "${sys}" | awk '$3 == "infralan" { print $5}'
    #
    # dhcpd-entry
    #
    installSrv="$LandscapeNFSSERVER"
echo "LandscapeBootString=${LandscapeBootString}"
    SystemBootString=${LandscapeBootString:-autoyast=nfs://@@INSTSRV@@/@@LSAYDIR@@/@@SYSTEM@@-ay.xml netdevice=eth0 netsetup=dhcp instmode=cd}
echo "SystemBootString=${SystemBootString}"
    # TODO: add more replace instructions like for IP, netmask and so
    SystemBootString=$(echo $SystemBootString | sed \
                              -e "s/@@INSTSRV@@/$installSrv/g" \
                              -e "s|@@LSAYDIR@@|$LandscapeNFS4AY|g" \
                              -e "s/@@SYSTEM@@/$sys/g" \
                         )
echo "SystemBootString=${SystemBootString}"
if [ -n "$sys" ]; then
    cat <<EOF >>/tmp/dhcpd.hosts.$$
    host ${sys} { hardware ethernet ${mac}; fixed-address ${ip}; option host-name "${sys}"; } 
EOF
fi
    #
    # pxe client config file
    # TODO: nfs-server, netdev and/or complete boot string should come from the Landscape Repository
    #
    clientFile=$(printf "%02X" $(echo "${ip}" | tr '.' ' ' ))
    cat <<EOF >"${pxeRoot}/off.${clientFile}"
# ${sys}
default autoinst
display /pxelinux.cfg/message

label autoinst
    kernel ${bootLoader}/linux
    append initrd=${bootLoader}/initrd ${SystemBootString}
EOF

done 

#
# dhcpd
#
cp /etc/dhcpd.conf /etc/dhcpd.conf.$$
skip=0
(
  while read dhcpcfg; do
    if [ "$skip" -eq 0 ]; then
        echo "$dhcpcfg"
    fi
    case "$dhcpcfg" in
        *LS-BEGIN* )
                   skip=1
                   cat /tmp/dhcpd.hosts.$$
                   ;;
        *LS-END* )
                   echo "$dhcpcfg"
                   skip=0
                   ;;
    esac

  done < /etc/dhcpd.conf
) > /etc/dhcpd.conf.edit
mv /etc/dhcpd.conf.edit /etc/dhcpd.conf
systemctl restart dhcpd
rm /tmp/dhcpd.hosts.$$
