#!/bin/sh
# This script hashes and encodes a given password, which can
# then be used for a devicestack user. It is intended for use
# by the restore-templates init script.
#
# To set this password to a user, save the output in a file
# like the following: /opt/userdata/devicestack/user/<username>
# Notice that the file (and the user) will be gone after a
# factory reset!
#
# While the deprecated format only contains the encoded password,
# the content of the file should look like this:
# pwd:<script_output>

# We expect exatly one argument--the password
if [ "$#" -ne 1 ]; then
	printf "Usage: ./encode-pw.sh <password>\\n"
	exit 1
fi

PASS="$1"
SALT=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 32 | head -n 1)

# If $SALT is not a 32 character string, something went wrong
if [ $(printf "%s" "${SALT}" | wc -c) -ne 32 ]; then
	printf "Error when generating salt, aborting!\\n"
	printf "Faulty salt: %s\\n" "${SALT}"
	exit 1
fi

# line by line, this command does the following:
# - concatenate password and salt
# - generates the sha256 sum of that and cuts off the filename
# - converts the hashsum from hex representation into binary format
# - generates the base64 of that (without trailing "=") and concatenates the salt
ENCODED_PASS=$(printf "%s%s" "${PASS}" "${SALT}"\
	| sha256sum | head -c64 \
	| sed 's/../\\\\x&/g' | xargs printf '%b' \
	| base64 | head -c43)${SALT}

printf "%s" "$ENCODED_PASS"

exit 0
