#!/bin/sh
#
# pwgen - generate a password of N length

usage() {
  printf '%b' "\
  pwgen - generate a password of N length

  generate random characters by reading \140/dev/urandom\140 with tr(1) command
  to translate the random bytes into a configurable character set.

  dd(1) command is then used to read only the desired length.

  \$1 = number of chars to receive (default: 50)
  \$2 = filter for the chars

  regarding usage of \140/dev/urandom\140 instead of \140/dev/random\140
  see: <https://www.2uo.de/myths-about-urandom/>
"
}

while getopts ':h' opt; do
  case "${opt}" in
    h)
      usage
      exit 0
      ;;
    *)
      printf '%s: Unrecognized option -%s\n' "${0##*/}" "${OPTARG}" >&2
      exit 1
      ;;
  esac
done
shift "$((OPTIND - 1))"

pass_length="$1"

pass=$(LC_ALL=C tr -dc "A-Za-z0-9-_" </dev/urandom \
  | dd ibs=1 obs=1 count="${pass_length:-50}" 2>/dev/null)
printf '%b' "${pass}"
