# Helper functions that can be useful for multiple scripts

# random: Create a random string in a specified format
# Usage: random format
# Where format is a string to be transformed into a random sequence:
# 	0 - transformed into a digit (0-9)
#	x - transformed into a lower case hexadecimal digit (0-9, a-f)
#	X - transformed into an upper case hexadecimal digit (0-9, A-F)
#	a - transformed into a lower case letter (a-z)
#	A - transformed into an upper case letter (A-Z)
#	l - transformed into a letter (upper or lower case) (a-z, A-Z)
#	L - transformed into a letter (upper or lower case) or number (a-z, A-Z, 0-9)
#	\ - skipped; next character is not transformed
#	anything else - kept as is
# e.g. to create a plane UUID, use
# random 
random() {
	local TEMPLATE="$1"
	local RESULT=""
	local KEEPNEXT=false
	local ADD
	for i in $(echo $TEMPLATE |fold -w1); do
		if $KEEPNEXT; then
			RESULT="$RESULT$i"
			KEEPNEXT=false
			continue
		fi
		case "$i" in
		x)
			ADD="$(echo $((RANDOM%16))|xargs printf '%x')"
			;;
		X)
			ADD="$(echo $((RANDOM%16))|xargs printf '%X')"
			;;
		0)
			ADD="${RANDOM:0:1}"
			;;
		a)
			ADD="$(head -n1 /dev/urandom |tr -dc a-z |cut -b1)"
			;;
		A)
			ADD="$(head -n1 /dev/urandom |tr -dc A-Z |cut -b1)"
			;;
		l)
			ADD="$(head -n1 /dev/urandom |tr -dc a-zA-Z |cut -b1)"
			;;
		L)
			ADD="$(head -n1 /dev/urandom |tr -dc a-zA-Z0-9 |cut -b1)"
			;;
		"\\")
			KEEPNEXT=true
			continue
			;;
		*)
			ADD="$i"
			;;
		esac
		RESULT="$RESULT$ADD"
	done
	echo -n $RESULT
}
