#!/bin/bash

# they say it's code guessing time.. it's been a while
# though so my knowledge of the game rules might be a
# little rusty... anyway we shall break ties

CurrentTime="$(date)"

echo This program will resolve a tie in the game \"Code Guessing\", found at https://cg.esolangs.gay/
echo

# first Obtain a "round number".  donno whats  it for but task says it's given

echo Please enter the \# of the round.

read -p '> ' round
echo

# we ask the user for "discord ids"

echo Please enter a number of Discord IDs.

export gamers="$({
	{
		while read -p '> ' ID
		do
			if [ $((ID)) -le 0 ]
			then
				break
			fi

			echo $((ID))
		done
	} | {
		# then we sort them

		sort -n
	}
})"

echo

# then we obtain the the last twitter of the Prime Minister of United Kingdom

echo Please open the twitter page of the current Prime Minister of United Kingdom.
echo At the time of writing this code, this is: https://twitter.com/Keir_Starmer
echo Obtain a tweet containing text authored by the PM and type it below.
printf 'The tweet must be newer than "%s".\n' "$CurrentTime"
echo
echo '<<TWEET_EOF'

export tweet_hash=$(
	while IFS= read -r LINE
	do
		if [ "$LINE" = "TWEET_EOF" ]
		then
			break
		fi

		printf '%s\n' "$LINE"

		# And hash it
	done | sha256sum | grep -o '^[^ ]*'
)

echo

echo Hash: $tweet_hash
echo

# divide "H" by "N"
# division is hard, we will use python for this
# also use python for Outputs.

"$(command -v python3 || command -v python)" <<EOF
import os

gamers = os.getenv('gamers').split('\n')
H = int(os.getenv('tweet_hash'), 16)
N = len(gamers)

print('Tie winner is:', gamers[H % N])
EOF
