#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
		Usage:
		  gen-password [LENGTH]
		  gen-password -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -h, --help    show this message

		  LENGTH        the length of the generated password
		                (default: 999)


		Generate a random password, and emit it to STDOUT.


		Examples:

		  Create a file with a secret:

		    $ gen-password > secret.txt


		  Generate an absurdly long secret:

		    $ gen-password 9999 > giant-secret.txt
	EOF
}


for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

while getopts 'h' flag; do
	case "$flag" in
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))

LENGTH="${1:-999}"

tr -cd '[:alnum:]' < /dev/urandom |
	fold -w "$LENGTH" |
	head -n1
