#!/usr/bin/env bash
# © Copyright EnterpriseDB UK Limited 2015-2026 - All rights reserved.
#
# hostnames 33
#   Returns 33 randomly-selected hostnames
#
# hostnames 33 /usr/share/dict/words
#   Returns 33 randomly-selected hostnames from /usr/share/dict/words
#
# hostnames 33 /usr/share/dict/words '^[a-m]{3}[n-z]{3,4}$'
#   Returns 33 randomly-selected hostnames from /usr/share/dict/words
#   that match the given pattern

IFS=$' \t\n'
set -eu

libdir=$(dirname "$0")
wanted=${1:?Number of hostnames not specified}
defaultnamesfile="$libdir/hostnames.txt"
namesfile=${2:-${HOSTNAMES_FROM:=$defaultnamesfile}}
pattern=${3:-${HOSTNAMES_PATTERN:='[a-zA-Z0-9-]+( +[0-9a-f.:]+)?( +[0-9a-f.:]+)?'}}
order=${HOSTNAMES_SORTED_BY:---random-sort}

sortcmd="sort"
if [[ ( ${HOSTNAMES_UNSORTED:-'False'} == 'True')  || ( $namesfile != "$defaultnamesfile" ) ]]; then
    sortcmd="cat"
    order=-
fi

type realpath &>/dev/null && namesfile=$(realpath "$namesfile")
if [[ ! -f $namesfile ]]; then
    echo "ERROR: could not open hostname list: $namesfile" >&2
    exit 1
fi

names=()
while IFS='' read -r line; do names+=("$line"); echo $line; done < \
    <(grep -xE "$pattern" "$namesfile"|"$sortcmd" "$order"|head -"$wanted")

if [[ "${#names[@]}" -lt $wanted ]];
then
    echo "ERROR: found only ${#names[@]}/$wanted names matching '$pattern' in $namesfile" >&2
    exit 1
fi
