#!/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
#
#######################################################
#
# Version 3.0.2018.03.21.1
#
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 'HYP SYSTEM' --system "$systemDef"; printf "\n")
    if [ -n "$help1" ]; then
        if [ ${#allSystems[@]} -gt 0 ]; then
            allSystems=( "${allSystems[@]}" "$help1" )
        else 
            allSystems=( "$help1" )
        fi
    fi
done

for s in "${allSystems[@]}"; do
    read hyp sys X <<< "$s"
    if [ "$hyp" = "$HOSTNAME" ]; then
        ssh_or_local="bash"
    else
        ssh_or_local="ssh -T root@$hyp"
    fi
    $ssh_or_local <<EOF
        if virsh list | grep -qw $sys; then
            echo "Destroy $sys"
            virsh destroy $sys
        fi
        if virsh domid $sys 1>/dev/null 2>/dev/null; then
            echo "Undefine $sys"
            virsh undefine $sys
        fi
EOF
done
