#!/usr/bin/env bash
# rpw -- generate a random password

. lib.bash || exit

usage() {
	echo "Usage: ${0##*/} [-c] [-l] [<length>]"
	echo ""
	echo "Generates a random password."
	echo ""
	echo "  -c        copy password to clipboard"
	echo "  -l        use only lowercase characters"
	echo ""
	echo "If length is negative, characters will be in dash-separated groups."
}

length=-20
dash=0
lcase=0
clip=0

for arg; do
	case $arg in
	--help)		usage; exit;;
	-c)		clip=1;;
	-l)		lcase=1;;
	-[0-9]*)	length=$arg;;
	[0-9]*)		length=$arg;;
	*)		vdie "bad argument '$arg'";;
	esac
done

if (( length < 0 )); then
	dash=1
	length=$(( -length ))
fi

pw=$(tr -dc 'A-Za-z0-9' < /dev/urandom | head -c "$length")

if (( lcase )); then
	pw=${pw,,}
fi

if (( dash )); then
	pw=$(printf '%s\n' "$pw" | sed -r 's/.{5}/&-/g; s/-$//')
fi

if (( clip )); then
	printf '%s' "$pw" | gclip
fi

printf '%s\n' "$pw"
