#!/bin/bash

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


##########################
function ymc_script_help
{
  echo "" 1>&2
  echo "Get services in Fliwi" 1>&2
  echo "" 1>&2
  echo "Usage: $(basename $0) [OPTIONS] hostname|service" 1>&2
  echo "=====" 1>&2
  echo "" 1>&2
  echo "OPTIONS:" 1>&2
  echo "========" 1>&2
  echo "--limit=<service|hostname>" 1>&2
  echo "  Limit listings to a specific services or hostname." 1>&2
  echo "" 1>&2
  echo "--as-hostnames" 1>&2
  echo "  Output hostnames instead of services." 1>&2
  echo "" 1>&2
  echo "--network=NETWORK-NAME" 1>&2
  echo "  Only list services in network 'NETWORK-NAME'." 1>&2
  echo "" 1>&2
  echo "" 1>&2
  echo "DEBUGGING OPTIONS:" 1>&2
  echo "==================" 1>&2
  echo "NOTE: The following are most likely only useful for debugging purposes." 1>&2
  echo "      Try not to use them on any productive environment!" 1>&2
  echo "" 1>&2
  echo "--nameserver=<someIP>" 1>&2
  echo "  Overrides the nameserver used in automatic detection of settings." 1>&2
  echo "  Default is to use the systems default nameserver." 1>&2
  echo "" 1>&2
}


help=""
as_hostnames=0
limit=""
network=""

TEMP=$(getopt -o h --long help,as-hostnames,nameserver:,limit:,network: \
              -n "$(basename $0)" -q -- "$@")
if [ $? != 0 ]; then
  ymc_script_help
  exit 1
fi

eval set -- "$TEMP"

while true
do
  case "$1" in
    -h|--help)
      ymc_script_help
      exit 1
    ;;

    --as-hostnames)
      as_hostnames=1
      shift 1
    ;;

    --nameserver)
      DEBUG_DNS=$2
      shift 2
    ;;

    --limit)
      limit=$2
      shift 2
    ;;

    --network)
      network=$2
      shift 2
    ;;

    --)
      shift
      break
    ;;

    *)
      ymc_script_help
      exit 1
    ;;
  esac
done

hostname=$*
if [ "$hostname" == "" ] || \
   [ $(echo $hostname | wc -w) -ne 1 ]; then
  ymc_script_help
  exit 1
fi



roles_found=0
roles_to_output=''
if [ $as_hostnames -eq 1 ]; then
  limit_grep_string='^'$limit'$'
  dns_part="hosts.services"
else
  limit_grep_string='^'$limit'-[0-9]+'
  dns_part="services"
fi
if [ "$network" != '' ]; then
  dns_part=$network"-"$dns_part
fi
found_roles=$(ymc_get_hostname_from_dns_txt "$hostname" "$dns_part")
if [ $? -eq 0 ] && [ "$found_roles" != '' ]; then
  for role in $found_roles
  do
    if [ "$role" != '' ]; then
      if [ "$limit" != '' ]; then
        if [ $(echo $role | grep -c -E -e "$limit_grep_string") -eq 1 ]; then
          roles_found=$(expr $roles_found + 1)
          roles_to_output=$roles_to_output' '$role
        fi
      else
        roles_found=$(expr $roles_found + 1)
        roles_to_output=$roles_to_output' '$role
      fi
    fi
  done
else
  exit 1
fi

if [ $roles_found -gt 0 ]; then
  for role_to_output in $roles_to_output
  do
    #if [ $as_hostnames -eq 0 ]; then
    #  echo $role_to_output
    #else
    #  echo OOPS:$role_to_output
    #fi
    echo $role_to_output
  done
  exit 0
else
  exit 1
fi
