#!/bin/sh

# Script to generate REST API credentials. These will be written to stdout,
# you can redirect stdout to etc/restapi.secret

# Exit on any error:
set -e

# The API URL is derived from the configured base URL, so that a judgedaemon
# talks to the installation this file belongs to. DOMJUDGE_RESTAPIURL is
# passed in by the makefiles; the fallback applies when run by hand.
RESTAPIURL="${DOMJUDGE_RESTAPIURL:-http://localhost/domjudge/api}"

# In a linked git worktree, reuse the judgehost password of the main
# checkout (see gen_all_secrets), so that one judgedaemon configuration can
# list all worktrees. The API URL stays this installation's own.
origin="Randomly generated"
passwd=
mainfile="${DOMJUDGE_MAIN_ETCDIR:-}/restapi.secret"
if [ -n "${DOMJUDGE_MAIN_ETCDIR:-}" ] && [ -r "$mainfile" ]; then
	# Like the webapp, use the first non-comment line.
	passwd=$(awk '!/^[[:space:]]*(#|$)/ { if (NF == 4) print $4; exit }' "$mainfile")
	[ -z "$passwd" ] || origin="Password copied from '$mainfile'"
fi
if [ -z "$passwd" ]; then
	passwd=$(head -c24 /dev/urandom | base64 | head -c32 | tr -dc 'A-Za-z0-9!"#$%&'\''()*+,-./:;<=>?@[\]^_`{|}~')
fi

echo "# $origin on host $(hostname), $(date)"
echo "# Format: '<ID> <API url> <user> <password>'"

printf "default\\t%s\\tjudgehost\\t%s\\n" "$RESTAPIURL" "$passwd"
