#!/bin/sh

# Script to generate database passwords. Passwords will be written to stdout,
# you can redirect stdout to etc/dbpasswords.secret

# Exit on any error:
set -e

# The database name and user default to the name of this DOMjudge instance,
# so that multiple instances on one host do not end up sharing a database.
# DOMJUDGE_INSTANCE is passed in by the makefiles; the fallback applies when
# this script is run by hand.
INSTANCE="${DOMJUDGE_INSTANCE:-domjudge}"

host=localhost
user="$INSTANCE"
passwd=
port=3306
origin="Randomly generated"

# In a linked git worktree, reuse the database host, user and password of
# the main checkout (see gen_all_secrets), so that one set of credentials,
# e.g. in a database GUI, gives access to the databases of all worktrees.
# Only the database name differs.
mainfile="${DOMJUDGE_MAIN_ETCDIR:-}/dbpasswords.secret"
if [ -n "${DOMJUDGE_MAIN_ETCDIR:-}" ] && [ -r "$mainfile" ]; then
	# Like dj_setup_database, use the last non-comment line.
	line=$(grep -v '^#' "$mainfile" | tail -n 1)
	IFS=: read -r _ mainhost maindb mainuser mainpasswd mainport _ <<LINE
$line
LINE
	if [ "$maindb" = "$INSTANCE" ]; then
		echo "Error: database '$maindb' of the main checkout would be shared with this worktree;" >&2
		echo "pass a different --with-instance-name=NAME." >&2
		exit 1
	fi
	if [ -n "$mainuser" ] && [ -n "$mainpasswd" ]; then
		host="$mainhost"
		user="$mainuser"
		passwd="$mainpasswd"
		port="${mainport:-3306}"
		origin="Credentials copied from '$mainfile'"
	fi
fi

if [ -z "$passwd" ]; then
	passwd=$(head -c12 /dev/urandom | base64 | head -c16 | tr '/+' 'Aa')
fi

echo "# $origin on host $(hostname), $(date)"
echo "# Format: 'unused:<db_host>:<db_name>:<user>:<password>:<db_port>'"

printf "unused:%s:%s:%s:%s:%s\n" "$host" "$INSTANCE" "$user" "$passwd" "$port"
