#!/bin/sh

dependnecy_satisfied=$({

	if [ -e /dev/null ]; then
		false
	else
		printf "/dev/null required but not found!!\n" >&2
		echo 0
	fi

	if [ -e /dev/stdin ]; then
		false
	else
		printf "/dev/stdin required but not found!!\n" >&2
		echo 0
	fi

	echo '[ <([ ]) ]' |. /dev/stdin 2>/dev/null>/dev/null;
	if [ ! $? -ne 0 ]; then
		false
	else
		printf "<( ) bashism required but not found!!\n" >&2
		echo 0
	fi

	if [ -e /dev/urandom ]; then
		false
	else
		printf "/dev/urandom required but not found!!\n" >&2
		echo 0
	fi

	if command -v openssl >/dev/null 2>&1; then
		false
	else
		printf "OpenSSL required but not found!!\n" >&2
		echo 0
	fi

	if command -v c++ >/dev/null 2>&1; then
		false
	else
		printf "C++ required but not found!!\n" >&2
		echo 0
	fi

	if command -v xxd >/dev/null 2>&1; then
		false
	else
		printf "xxd required but not found!!\n" >&2
		echo 0
	fi

	if command -v head >/dev/null 2>&1; then
		false
	else
		printf "head required but not found!!\n" >&2
		echo 0
	fi

	if command -v cat >/dev/null 2>&1; then
		false
	else
		printf "cat required but not found!!\n" >&2
		echo 0
	fi
	
	if command -v mkdir >/dev/null 2>&1; then
		false
	else
		printf "mkdir required but not found!!\n" >&2
		echo 0
	fi

	if command -v realpath >/dev/null 2>&1; then
		false
	else
		printf "realpath required but not found!!\n" >&2
		echo 0
	fi

	if command -v dirname >/dev/null 2>&1; then
		false
	else
		printf "dirname required but not found!!\n" >&2
		echo 0
	fi

	echo 1

})

if [ "$dependnecy_satisfied" = 1 ]
then
	false
else
	printf "FATAL: unsatisfied. dependnecy\n\n" >&2
	exit 1
fi

cd "$(dirname "$(realpath $0)")"

AMOGUS_ROOT=amoguses_"$(cat /dev/urandom | head -c 8 | xxd -p)"
mkdir -p "$AMOGUS_ROOT"
c++ ./slow_but_reliable.cpp -O0 -o "$AMOGUS_ROOT"/slow_but_reliable
c++ ./fast_but_sussy.cpp -O2 -o "$AMOGUS_ROOT"/fast_but_sussy

random_salt=$(cat /dev/urandom | head -c 8 | xxd -p)

secure_hash() {
	openssl kdf \
		-keylen 32 \
		-kdfopt digest:SHA256 \
		-kdfopt pass:"$(cat /dev/stdin)" \
		-kdfopt salt:$random_salt \
		-kdfopt iter:1000000 PBKDF2
}

desussify() {
	while true
	do
		trusted=$(head -c 1 $1);
		sussy=$(head -c 1 $2);
		trusted_hash=$(printf "%llx" $trusted | secure_hash)
		sussy_hash=$(printf "%llx" $sussy | secure_hash)
		if [ $trusted_hash = $sussy_hash ]
		then
			no_longer_sussy=$sussy
			printf "%llx" $no_longer_sussy;
		else
			printf "FATAL: sussy amogus\n" >&2
			exit 1
		fi
	done
}

{ sleep 0.01 && rm -rf "$AMOGUS_ROOT"; } &
	# sussy race condition: amoguses might get voted out before we run them
	# added a large delay to mitigate.

desussify \
	<("$AMOGUS_ROOT"/slow_but_reliable) \
	<("$AMOGUS_ROOT"/fast_but_sussy)
