#!/bin/ksh
# olbohlen, 2020-04-17 in corona seperation...
# for my personal setup build a dynamic inventory of all ldoms and zones

# --list is default action
# fake --host operation by printing an empty dictionary
if [ "x$1" == "x--host" ]; then
    printf "{}\n"
    exit 0
fi  

domain=eenfach.de
primary="prigw-vsw"

# get a list of ldoms
ldoms=$(ssh ${primary}.${domain} /usr/sbin/ldm list -p | nawk -F "|" '$1~/^DOMAIN$/ { split($2,a,"="); print a[2]}' 2>/dev/null)

#ldoms="prod dev"

# open JSON structure
printf "{\n"

# print the "all" group
printf "\"all\": {\n\"children\": ["
for ldom in ${ldoms}; do
    printf "%s\n\"%s\"" "${comma}" "${ldom}eenfachzones"
    comma=","
done
comma=""
printf ",\n\"eenfachldoms\"\n]\n},\n"

# print the eenfachzones
printf "\"eenfachzones\": {\n\"children\": ["
for ldom in ${ldoms}; do
    printf "%s\n\"%s\"" "${comma}" "${ldom}eenfachzones"
    comma=","
done
comma=""
printf "\n]\n},\n"

# print ldoms group
printf "\"eenfachldoms\": {\n\"hosts\": ["
for ldom in ${ldoms}; do
    printf "%s\n\"%s.%s\"" "${comma}" "${ldom}" "${domain}"
    comma=","
done
comma=""
printf "\n]\n},\n"



# print a zone group for every ldom
for ldom in ${ldoms}; do
    printf "%s\n\"%s%szones\": {\n\"hosts\": [" "${comma}" "${ldom}" "${domain%%.*}"
    # not a bug, initialize $comma after here to have it only on
    # runs *after* first run
    comma=","
    #FIXME make the ssh hostname more generic
    for zone in $(ssh ${ldom}gw-est.eenfach.de /usr/sbin/zoneadm list -ci 2>/dev/null| grep -v global); do
	printf "%s\n\"%s.%s\"" "${commaz}" "${zone}" "${domain}"
	commaz=","
    done
    printf "]\n}"
    commaz=""
done

# close JSON structure
printf "\n}\n"
