#!/bin/bash

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


##########################
function ymc_script_help
{
  echo ""
  echo "Get a list of packages that should be installed in Fliwi"
  echo ""
  echo "Usage: $(basename $0) [OPTIONS] hostname|service"
  echo "====="
  echo ""
  echo "OPTIONS:"
  echo "========"
  echo "-s|--service-based-lookup"
  echo "  Get packages for services. If not given, it is assumed to get"
  echo "  host-based package-information."
  echo ""
  echo "--show-[name]"
  echo "  Only output a specific type of information. If not given, all available"
  echo "  will be shown."
  echo ""
  echo "--limit=PACKAGE_NAME"
  echo "  Limit to a specific package name of a service or host."
  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 ""
}


dns_part="hosts.packages"
show_all=1
show_name=0
show_uid=0
show_shell=0
show_home=0

TEMP=$(getopt -o hs --long help,service-based-lookup,nameserver:,limit:,show-name \
              -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
    ;;

    -s|--service-based-lookup)
      dns_part="services.packages"
      shift 1
    ;;

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

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

    --show-name)
      show_name=1
      show_all=0
      shift 1
    ;;

    --)
      shift
      break
    ;;

    *)
      ymc_script_help
      exit 1
    ;;
  esac
done

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

### We currently do not support per service-node package-configs
what_to_lookup_for=$(echo $what_to_lookup_for | sed -r 's/-[0-9]+$//')

packages_to_print_details=""

found_packages=$(ymc_get_hostname_from_dns_txt "$what_to_lookup_for" "$dns_part")
if [ $? -eq 0 ] && \
   [ "$found_packages" != '' ]; then
  for package_name in $found_packages
  do
    if [ "$package_name" != '' ]; then
      if [ "$limit_string" != '' ]; then
        if [ "$limit_string" != "$package_name" ]; then
          continue
        fi
      fi
      echo $package_name
    fi
  done
else
  exit 1
fi

