#!/sbin/openrc-run

description="OIDC authentication service for OpenVPN"

: ${command_user:="openvpn-auth:openvpn-auth"}
: ${cfgfile:="/etc/openvpn-auth-oauth2/config.yaml"}
: ${generate_http_secret:=yes}

command="/usr/bin/openvpn-auth-oauth2"
command_args="--config $cfgfile $command_args"
command_background="yes"
pidfile="/run/$RC_SVCNAME.pid"
no_new_privs="yes"

required_files="$cfgfile"

depend() {
	need net
	use openvpn
}

start_pre() {
	if yesno "$generate_http_secret"; then
		local http_secret="${cfgfile%/*}/http-secret.txt"

		if ! [ -e "$http_secret" ]; then
			einfo "Writing random secret to $http_secret..."
			gen_pass | install -m 640 -g "${command_user#*:}" /dev/stdin "$http_secret"
		fi
	fi
}

gen_pass() {
	head /dev/urandom | tr -dc A-Za-z0-9 | head -c 32
}
