#!/usr/bin/env bash

LENGTH=$1
LENGTH=${LENGTH:=12}

  
is_number() {

   return $(test ! -z "${1##*[!0-9]*}" > /dev/null 2>&1);

   # - also possible
   # -
   #[[ ! -z "${1##*[!0-9]*}" ]] && return 0 || return 1
   #return $([[ ! -z "${1##*[!0-9]*}" ]])
}


regexp_digit="([23456789].*){2}"
regexp_special_char="([-_/\.%+~].*){2}"
regexp_not_alowed="([0ODl18B])"

if ! is_number $LENGTH ; then
	echo ""
	echo "   [ Error]: Given parameter for password length '$LENGTH' is NOT a positiv Number!"
	echo ""
	exit 1
fi

if [[ $LENGTH -le 9 ]]; then
	echo ""
	echo "   [ Error]: Given parameter for password length '$LENGTH' is too short!"
	echo "             Minimum length is '10'."
	echo ""
	exit 1
fi
	


for ((i=0; i<=9; i++)); do 

   while [ 1 ] ; do

      # - Generate Passwort
      _passwd="$(head -c 300 /dev/urandom | tr -cd 'a-zA-Z0-9-_/\.%+~' | head -c $LENGTH)"
      #echo "$_passwd"

      # - Check Password
      # -
      if [[ "$_passwd" =~ $regexp_not_alowed ]] ; then
         continue
      fi
      if [[ ! "$_passwd" =~ $regexp_special_char ]] ; then
         continue
      fi
      if [[ ! "$_passwd" =~ $regexp_digit ]] ; then
         continue
      fi

      echo -n "$i: " 
      echo "$_passwd"

      break

   done
   
done

exit 0
