#!/bin/bash

# Copyright (c) Veeam Software Group GmbH

set -eE -u -o pipefail

SCRIPT_DIR=$(dirname "$(realpath "${BASH_SOURCE[0]}")"); readonly SCRIPT_DIR;
source "$SCRIPT_DIR/lib/error-handle.bash"
source "$SCRIPT_DIR/lib/optparser.bash"

setlocale en_US.utf8 || :

# shellcheck disable=SC2034
declare -A op=()
declare -A ARGS=()
optparser-init op \
    --desc "STIG-compliant password generator."
optparser-addopt op --name "length" --narg '?' --default 16 \
    --help "password length"
optparser-addopt op -s "-h" -l "--help" \
    --help "show this help message and exit"
optparser-ignore-required op help
optparser-parse op ARGS "$@" || exit 1
[[ -n ${ARGS[help]:-} ]] && { optparser-help op; exit 0; }
[[ ${ARGS[length]} =~ ^[0-9]+$ ]] || die "length must be a positive integer greater than 15"
(( ARGS[length] > 15 )) || die "length must be a positive integer greater than 15"

set +o pipefail
tr -cd '[:alnum:]!@$^&*+=_%#-' < /dev/urandom \
    | fold -w "${ARGS[length]}" \
    | sed -n -e '/[0-9]/!b' \
             -e '/[a-z]/!b' \
             -e '/[A-Z]/!b' \
             -e '/[!@$^&*+=_%#-]/!b' \
             -e '/\(.\)\1\{3,\}/b' \
             -e 'p;q'
