#!/bin/sh

[ -t 1 ] || init-crypto 2> /dev/null > /dev/null

# FUNCTIONS ###########################################################

# script usage
usage() {
    >&2 cat <<EOF
ADLIN token generator
EOF
}

# token generator
token_generator() {
    {
	echo -n ${PKEY}
	for d
	do
	    echo -n :${d}
	done
    } | sha512sum | cut -d ' ' -f 1
}

# JSON token format helper
token_format() {
    local TID=$1
    local TOKEN=$2
    shift 2

    [ $# -gt 0 ] && {
	local DATA=',
    "data": [';
	for d; do
	    [ -z "$Z" ] && Z=1 || DATA="$DATA, "
	    DATA="$DATA\"$d\""
	done
	DATA="$DATA]"
    }

    local challenge=
    [ -z "${TID}" ] || {
	challenge="
    \"challenge\": ${TID},"
    }

    # There is a hidden bonus if you send adlin 42 to
    # adlin.nemunai.re/toctoc
    cat <<EOF
{
    "login": "${ULGN}",${challenge}
    "token": "${TOKEN}"${DATA}
}
EOF
}

# /proc/cmdline parser (from Gentoo Wiki)
cmdline() {
    local value
    value=" $(cat /proc/cmdline) "
    value="${value##* $1=}"
    value="${value%% *}"
    [ "$value" != "" ] && echo "$value"
}


# GLOBAL VARIABLES ####################################################

ULGN=$(cmdline adlin.login)
PKEY=$(cmdline adlin.key)


# MAIN ################################################################

[ $# -lt 1 ] && { usage; exit 1; }

TOKENID="$1"
case "${TOKENID}" in
    token1|token2)
	HDATA=42
	;;
    token3|token5)
	DATA=$(date +%s%N)
    ;;
    bonus2)
	echo "${TOKENID} is not here! Perhaps it has been accidentally deleted?" >&2
	exit 2
    ;;
    token4)
	if [ -t 0 ]; then
	    HDATA=$(dig +short +time=1 +tries=0 adlin.nemunai.re $2) || {
		echo "Try again! Your resolver settings seems not good :(" >&2
		exit 3
	    }
	else
	    read HDATA
	fi
	HDATA=$(echo "${HDATA}" | sed 's/["\\]//g')
	echo $HDATA | grep "not here" 2> /dev/null && exit 3
    ;;
    *)
	DATA=$@
	TOKENID=
	;;
esac

if [ -n "${TOKENID}" ]
then
    TOKENID="${TOKENID#token}"
    if [ "$TOKENID" -ne "${TOKENID#bonus}" ]
    then
	TOKENID="${TOKENID#bonus}"
	TOKENID=$(($TOKENID + 5))
    fi
fi

token_format "${TOKENID}" "$(token_generator ${TOKENID} ${HDATA} ${DATA})" ${DATA}
