#!/bin/bash
set -euo pipefail

echo "Creation of a OTP key"
read -r -p "User name [$(id -urn)]: " USERNAME
read -r -p "System/service name: [$(hostname)]: " SERVICE
read -r -p "Window/interval (in seconds) [30]: " INTERVAL
read -r -p "Digits in code [6]:" DIGITS
readonly USERNAME=${USERNAME:-$(id -urn)} SERVICE=${SERVICE:-$(hostname)} INTERVAL=${INTERVAL:-30} DIGITS=${DIGITS:-6}

echo

echo "Creating random key..."
readonly KEY=$(head -30 /dev/urandom | sha256sum | cut -c 1-60)
readonly BASE32_KEY=$(echo ${KEY} | xxd -r -ps | base32)
echo "Key: ${KEY}"
echo "Key in base32: ${BASE32_KEY}"

echo

echo "Line to add to users file:"
echo "HOTP/T${INTERVAL}/${DIGITS} ${USERNAME} - ${KEY}"

echo

readonly URL="otpauth://totp/${USERNAME}@${SERVICE}?period=${INTERVAL}&digits=${DIGITS}&secret=${BASE32_KEY}"
echo "URL for easy set up in OTP applications:"
echo "${URL}"
if which qrencode > /dev/null ; then
	qrencode -t UTF8 "${URL}"
fi
