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

cp /etc/hosts /etc/hosts.fh.edit
export grepPatt=""
for s in "${allSystems[@]}"; do
    read sys ip X <<< "$s"
    grepPatt="${grepPatt}${grepPatt:+|}${sys}"
    echo "$ip $sys"
done >/etc/hosts.fh.add
(
  cat /etc/hosts | egrep -w -v "($grepPatt)" 
  cat /etc/hosts.fh.add
) >/etc/hosts.fh.edit
#rm /etc/hosts.fh.add
#mv /etc/hosts.fh.edit /etc/hosts
cp /etc/hosts.fh.edit /etc/hosts
cp /etc/hosts.fh.edit /var/lib/Landscape/files/etc/hosts
