#!/bin/sh
#
# rdeps: ssh-tags

init_variables() {
  COMMAND=${0##*/}

  # HOSTS_TAGS_FILES are expected to have a YAML structure
  # similar to the following example
  #
  # frontend.example.com:
  #   project: website
  #   environment: test
  # backend.example.com:
  #   project: website
  #   environment: test
  #   purpose: backend
  # database.example.com: [invalid data]
  #
  # there is no restriction on the tags key
  # hosts don't have to have all the same tags
  HOSTS_TAGS_FILES="${XDG_DATA_HOME:-${HOME}/.local/share}/hosts_tags*.yaml"

  AWK_SCRIPT=
  QUERY_TYPE=hosts
  QUERY_ARGUMENTS=
}

parse_command_line() {
  if [ $# -gt 0 ]; then
    QUERY_TYPE="$1"
    shift
    QUERY_ARGUMENTS=$*
  fi
}

validate_command_line() {
  if [ "${QUERY_TYPE}" != 'tags' ] && [ "${QUERY_TYPE}" != 'hosts' ]; then
    exit_error "invalid query type ${QUERY_TYPE}"
  fi

  if [ "${QUERY_TYPE}" = 'tags' ] && [ -z "${QUERY_ARGUMENTS}" ]; then
    exit_error 'missing host argument'
  fi

  if [ "${QUERY_TYPE}" = 'hosts' ]; then
    for QUERY_ARG in ${QUERY_ARGUMENTS}; do
      case "${QUERY_ARG}" in
        ?*=?*) continue ;;
        *) exit_error "invalid tag value argument '${QUERY_ARG}'" ;;
      esac
    done
  fi
}

exit_error() {
  [ -z "$1" ] || echo "${COMMAND}: $1"
  exit 1
} >&2

query_tags() {
  AWK_SCRIPT="\$1 == \"$1\""
  AWK_SCRIPT="${AWK_SCRIPT} { for (i=2; i<=NF; i++) print \$i }"

  TAGS_VALUES=$(process_file)

  MAX_TAG_LENGTH=$(
    echo "${TAGS_VALUES}" \
      | awk 'BEGIN { FS="=" }
             { if (length($1) > max) { max = length($1) } }
             END { print max }'
  )

  echo "${TAGS_VALUES}" \
    | grep -v '^host' \
    | sed 's/=/\t/' \
    | expand -t "$((MAX_TAG_LENGTH + 2))"
}

query_hosts() {
  # shellcheck disable=SC2016
  AWK_SCRIPT='function any_tag_field_match_string(string)
              {
                for (i=2; i<=NF; i++)
                  if ($i == string) return 1
                return 0
              }
              1'
  while [ "$#" -gt 0 ]; do
    AWK_SCRIPT="${AWK_SCRIPT} && any_tag_field_match_string(\"$1\")"
    shift
  done
  AWK_SCRIPT="${AWK_SCRIPT} { print \$1 }"

  process_file
}

process_file() {
  # transform the YAML structure into multiline records
  # before awk processing
  #
  # frontend.example.com
  # project=website
  # environment=test
  # host=frontend.example.com
  #
  # backend.example.com
  # project=website
  # environment=test
  # purpose=backend
  # host=backend.example.com

  # shellcheck disable=SC2086
  sed \
    -e 's/^\([^ ][^:]*\):.*$/\n\1/' \
    -e 's/^  //' \
    -e 's/: /=/' \
    ${HOSTS_TAGS_FILES} \
    | awk \
      'BEGIN { FS="\n"; OFS="\n"; RS=""; ORS="\n\n" } { print $0, "host="$1 }' \
    | awk \
      'BEGIN { FS="\n"; OFS="\n"; RS=""; ORS="\n\n" } !visited[$1]++' \
    | awk \
      "BEGIN { FS=\"\n\"; RS=\"\" } ${AWK_SCRIPT}" \
    | sort
}

init_variables
parse_command_line "$@"
validate_command_line

# shellcheck disable=SC2086
"query_${QUERY_TYPE}" ${QUERY_ARGUMENTS}
