#!/usr/bin/bash
#
# Generate a repeatable password using a system wide seed
#

SEED=/etc/sysconfig/authseed

# If run as non-root sudo (this will use a derrived authseed based on the caller)
SUDOED=0

function usage {
	printf "Usage: %s [-f /path/to/authseed] <username-or-token> <length\n" $(basename $0) >&1
	exit 1
}

# Check if we have sudoed
if [ $# -lt 3 ]; then
	usage
elif [ "$1" == "--sudo" ]; then
	# We (claim) to be already sudoed
	SUDOED=1	
	shift;
elif [ "$1" == '-f' ]; then
	# -f is mutually exclusive with --sudo
	shift
	SEED="$1"
	shift
elif [ $(id -u) -ne 0 ]; then
	# We have no --sudo, no -f and no root, try to sudo
	sudo -n $(readlink -f $0) --sudo "$1" "$2"
	exit $?
fi

# Check we can read the authseed
if [ ! -r "$SEED" ]; then
	echo "Unable to read authseed file '$SEED'"
    	exit 1
fi
	
# Check the arguments
[ $# == 2 ] || usage

# Validate the token length
if [[ $2 -lt 1 || $2 -gt 128 ]]; then
	echo "Usage: $(basename $0) <username-or-token> <length>" >&2
	echo "   **  <length> must be between 1 and 128 characters" >&2
	exit 2
fi

if [ "$SUDOED" == "1" ]; then
	# We called via --sudo we generate an intermediate key first
	if [ -z "${SUDO_USER}" ]; then
		echo "Error: called via --sudo but can't determine sudo user"
		exit 3
	fi
	echo "$1" \
	  | sha512hmac -k <($(readlink -f $0) "sudo:${SUDO_USER}" 128) - \
	  | base64 \
	  | tr -dc 0-9A-Za-z \
	  | cut -c1-$2
else
	# We strip a trailing newline if present using perl chomp
	echo "$1" \
	| sha512hmac -k <(perl -pe 'chomp if eof;' ${SEED}) - \
	| base64 \
	| tr -dc 0-9A-Za-z \
	| cut -c1-$2
fi


