#!/bin/bash

### Include ymclibnettools
. /usr/lib/lib-fliwi/ymc-networktools.bash


##########################
function ymc_script_help
{
  echo ""
  echo "Get human admins for a host or a service in Fliwi"
  echo ""
  echo "Usage: $(basename $0) --hostname|--service [DEBUGGING OPTIONS] hostname|service"
  echo "====="
  echo ""
  echo "OPTIONS:"
  echo "========"
  echo "--hostname"
  echo "  Assume a hostname is given as input, mutually exclusive with --service"
  echo ""
  echo "--service"
  echo "  Assume a service is given as input, mutually exclusive with --hostname"
  echo ""
  echo ""
  echo "DEBUGGING OPTIONS:"
  echo "=================="
  echo "NOTE: The following are most likely only useful for debugging purposes."
  echo "      Try not to use them on any productive environment!"
  echo ""
  echo "--nameserver=<someIP>"
  echo "  Overrides the nameserver used in automatic detection of settings."
  echo "  Default is to use the systems default nameserver."
  echo ""
}

function ymc_initialise_script
{
  help=$(echo "$*" | grep -c '\--help')
  is_hostname=$(echo "$*" | grep -c '\--hostname')
  is_service=$(echo "$*" | grep -c '\--service')

  DEBUG_DNS=$(echo "$*" | grep -E -e '--nameserver=' | perl -pi -e 's/.*--nameserver=([^ ]+).*/$1/')

  service_or_hostname=$(eval echo \$$#)
  if [ "$service_or_hostname" == "$0" ]; then
    help=1;
  fi

  if [ $is_hostname -ne 1 ] && [ $is_service -ne 1 ]; then
    help=1;
  fi

  if [ $is_hostname -eq 1 ] && [ $is_service -eq 1 ]; then
    help=1;
  fi

  if [ $help -eq 1 ]; then
    ymc_script_help 1>&2
    exit 1
  fi
}


ymc_initialise_script $*
services=''
if [ $is_hostname -eq 1 ]; then
  temp_services=$(fliwi-get-services $service_or_hostname)
  for temp_service in $temp_services
  do
    services=$services' '$(echo $temp_service | sed -r 's/-[0-9]+$//')
  done
else
  services=$service_or_hostname
fi

dns_part="access"
dns_part_server="serveraccess"
admins_found=0;
admins_to_output=''

for service in $services
do
  found_admins=$(ymc_get_hostname_from_dns_txt "$service" "$dns_part")
  if [ $? -eq 0 ] && [ "$found_admins" != '' ]; then
    for admin in $found_admins
    do
      if [ "$admin" != '' ]; then
        admins_found=$(expr $admins_found + 1)
        admins_to_output=$admins_to_output' '$admin
      fi
    done
  fi
done

if [ $is_hostname -eq 1 ]; then
  found_admins=$(ymc_get_hostname_from_dns_txt "$service_or_hostname" "$dns_part_server")
  if [ $? -eq 0 ] && [ "$found_admins" != '' ]; then
    for admin in $found_admins
    do
      if [ "$admin" != '' ]; then
        admins_found=$(expr $admins_found + 1)
        admins_to_output=$admins_to_output' '$admin
      fi
    done
  fi
fi

admins_to_output=$(echo $admins_to_output | sed -r 's/ /\n/g' | sort | uniq)

if [ $admins_found -gt 0 ]; then
  for admin_to_output in $admins_to_output
  do
    echo $admin_to_output
  done
  exit 0
else
  exit 1
fi
