#!/bin/sh

create_pw_file()
{
	SCRIPT="$1"
	FILE="$2"

	if [ -f "$FILE" ]; then
		[ -n "$QUIET" ] || echo "Password file '$FILE' already exists, leaving untouched."
		return
	fi

	# shellcheck disable=SC2039
	[ -n "$QUIET" ] || printf "Running '%s'... " "$SCRIPT"
	touch "$FILE"
	chmod go= "$FILE"
	# Don't leave a partial file behind: it would be kept on the next run.
	if ! "./$SCRIPT" > "$FILE"; then
		rm -f "$FILE"
		exit 1
	fi
	[ -n "$QUIET" ] || echo "file '$FILE' created."
}

while getopts ':q' OPT ; do
	case "$OPT" in
		q)
			QUIET=1
			;;
		:)
			echo "Error: option '$OPTARG' requires an argument."
			exit 1
			;;
		?)
			echo "Error: unknown option '$OPTARG'."
			exit 1
			;;
		*)
			echo "Error: unknown error reading option '$OPT', value '$OPTARG'."
			exit 1
			;;
	esac
done
shift $((OPTIND-1))

# shellcheck disable=SC2164
cd "$(dirname "$0")"

# In a linked git worktree, the generators reuse the credentials of the main
# checkout where possible, so that one set of credentials works for all
# worktrees. Outside of a linked worktree, both git directories are the same.
gitdir=$(git rev-parse --path-format=absolute --git-dir 2>/dev/null) || gitdir=
commondir=$(git rev-parse --path-format=absolute --git-common-dir 2>/dev/null) || commondir=
if [ -n "$commondir" ] && [ "$gitdir" != "$commondir" ]; then
	DOMJUDGE_MAIN_ETCDIR="$(dirname "$commondir")/etc"
	export DOMJUDGE_MAIN_ETCDIR
fi
create_pw_file gendbpasswords dbpasswords.secret
create_pw_file genrestapicredentials restapi.secret
create_pw_file gensymfonysecret symfony_app.secret
create_pw_file genadminpassword initial_admin_password.secret
