#shellcheck disable=SC2034

set -e
set -o pipefail
# set -x

cd "$(dirname "$(readlink -f "$path")")" >&2

. util.sh

. ~/.bloginrc
. "$CASH_PATH"

ALLOWED_SIGNERS=$(cat <<EOF
blogin $(cat "$SIGN_PUB")
EOF
)

SESSION_TIME=${SESSION_TIME:-1 hour}

TITLE="blogin"

DESCRIPTION="the worst member of the logiverse"
AUTHOR="$USER"
TAGS=(meta interactive tadiweb)
WRITTEN_AT=2024-12-28T00:00:00Z

action=$(jq -r '.action // ""' <<< "$BLAG_QUERY" || :)
if [[ "${action:+x}" == "x" ]]; then
	RAW=application/json
fi

metadata

case "$action" in
	verify_token)
		#shellcheck disable=SC2266
		{
			verified=$(jq -r '.token // ""' <<< "$BLAG_QUERY" |	bwt_verify)
			[[ "$(jq -r '.till > now' <<< "$verified")" == "true" ]]
			printf '%s' "$verified"
		} || echo false
		exit
		;;

	posts)
		db_rows "SET TIME ZONE 'UTC'; SELECT * FROM posts" |
		jq -r 'map([.contents, .username, .ts, null, 0]) | select(. != [])'
		exit
		;;

	login)
		username=$(jq -r '.username' <<< "$BLAG_QUERY" || :)
		password=$(jq -r '.password' <<< "$BLAG_QUERY" || :)

		if ! printf '%s' "$username" | rg -Uq '^[a-zA-Z0-9_]{3,24}$'; then
			json_err "username must be between 3 to 24 characters, and must consist of alphanumerical characters plus underscore"
			exit
		elif ! printf '%s' "$password" | rg -Uq '^.{8,108}$'; then
			json_err "password must be between 8 and 108 characters"
			exit
		fi
		{
			query="SELECT password FROM users WHERE username=$(escape_sql_str "$username")"
			row=$(db_row "$query")
			if [[ "$row" == "null" ]]; then
				hash=$(printf '%s' "$password" | argon2_hash)
				echo "registering user $username" >&2
				unset password
				db_query "INSERT INTO users (username, password) VALUES ($(escape_sql_str "$username"), $(escape_sql_str "$hash")) ON CONFLICT (username) DO UPDATE SET password=excluded.password" >&2

				created=true
			else
				hash=$(jq -r '.password' <<< "$row")
				if ! argon2_verify "$hash" <<< "$password"; then
					json_err "invalid password"
					exit
				fi

				created=false
			fi

			json_username=$(jq -Rr @json <<< "$username")
			till=$(date -d "+ $SESSION_TIME" '+%s')

			printf '{"till":%s,"user":%s}' \
				"$till" \
				"$json_username" |
				bwt_sign |
				jq -R "{ error: false, created: $created, user: $json_username, till: $till,  token: . }"
		} || json_err

		exit
		;;

	submit)
		{
			token=$(jq -r '.token // ""' <<< "$BLAG_QUERY" || :)
			if ! verified=$(check_token "$token"); then
				json_err "$verified token"
				exit
			fi

			user=$(jq -r .user <<< "$verified")
			status=$(jq -r .status <<< "$BLAG_QUERY")
			chars=${#status}

			if (( chars == 0 || chars > 200 )); then
				json_err "status should be between 1 and 200 characters"
				exit
			fi

			db_query "SET TIME ZONE 'UTC'; INSERT INTO posts (username, contents, ts) VALUES (
				$(escape_sql_str "$user"),
				$(escape_sql_str "$status"),
				$(escape_sql_str "$(date -u --rfc-3339=seconds)")::timestamp
			) ON CONFLICT (username) DO UPDATE
				SET contents=excluded.contents, ts=excluded.ts" >&2
			echo '{"error":false}'
		} || json_err
		exit
		;;
esac

echo "<style>"
cat blogin.css
echo "</style>"

header 1 <<< "$TITLE"
paragraph <<< "$DESCRIPTION"

link "https://git.slonk.ing/slonk/blogin" <<< "view source" | paragraph

cat partials/submit.html
cat partials/login.html

echo '<div id="error"></div>'
echo '<div id="success"></div>'

header 2 <<< "posts"

echo '<div id="posts">loading...</div>'

#shellcheck disable=SC2162
#while read POST; do {
#	if [[ "${POST:+x}" == "x" ]]; then
#		declare -A post="$POST"
#		render partials/post.sh "${post[username]}" "${post[instance]}" "${post[timestamp]}" "${post[contents]}"
#	fi
#} & done < <(parse_posts "${INSTANCES[@]}" || :)
#
#wait

echo '<script>'
cat load.js
echo '</script>'
echo '<noscript>blogin needs javascript to run :(</noscript>'
