#!/bin/sh
set -eu

PROGNAME='setup-freeradius'
DEFAULT_MODULES='@@DEFAULT_MODULES@@'
# <subpkgname|module-name> <module-name>...
EXTRA_MODULES='
	dhcp
	eap inner-eap
	krb5
	ldap
	pam
	perl
	python3
	redis rediswho
	rest
	sql abfab_psk_sql dhcp_sqlippool sqlcounter sqlippool
	'
MODS_AVAILABLE_DIR='/etc/raddb/mods-available'
MODS_ENABLED_DIR='/etc/raddb/mods-enabled'
SITES_AVAILABLE_DIR='/etc/raddb/sites-available'
SITES_ENABLED_DIR='/etc/raddb/sites-enabled'


die() {
	echo "$PROGNAME: $2" >&2
	exit $1
}

find_mod_pkg() {
	echo "$EXTRA_MODULES" \
		| grep -m 1 -w "$1" \
		| sed -En 's/^\s*(\S+).*/freeradius-\1/p' \
		| grep .
}

case "${1:-}" in
	'' | -h | --help)
		cat >&2 <<-EOF
		Usage: $PROGNAME [-h | <action> [<args>...]]

		Enable/disable module or site creates/removes symlink in
		/etc/raddb/{mods,sites}-enabled/ directory. If the module <name>
		is provided by a separate freeradius-<name> package, then it
		installs/uninstalls the package.

		Actions:
		  enable-mod <name>    Enable the named module.
		  enable-default-mods  Enable all the default modules.
		  disable-mod <name>   Disable the named module.
		  enable-site <name>   Enable the named site.
		  disable-site <name>  Disable the named site.
		EOF
		exit 2
	;;
	enable-mod | enable-module)
		name=$2
		modlink="$MODS_ENABLED_DIR/$name"

		if [ -L "$modlink" ]; then
			exit 0
		fi
		if pkgname=$(find_mod_pkg "$name"); then
			apk add "$pkgname"
		fi
		if [ ! -L "$modlink" ] && [ -f "$MODS_AVAILABLE_DIR/$name" ]; then
			ln -sv ../mods-available/$name "$MODS_ENABLED_DIR/$name"
		else
			die 3 "module '$name' is not available!"
		fi
	;;
	disable-mod | disable-modules)
		name=$2
		modlink="$MODS_ENABLED_DIR/$name"

		if [ -L "$modlink" ] &&
			pkgname=$(apk info -q --who-owns "$modlink" 2>/dev/null) &&
			[ "$pkgname" = "freeradius-$name" ];
		then
			apk del "$pkgname"
		elif [ -L "$modlink" ]; then
			rm -v "$modlink"
		elif [ -e "$modlink" ]; then
			die 4 "$modlink is not a symlink!"
		fi
	;;
	enable-site)
		name=$2
		sitelink="$SITES_ENABLED_DIR/$name"

		[ -L "$sitelink" ] && exit 0
		[ -f "$SITES_AVAILABLE_DIR/$name" ] || die 3 "site '$name' is not available!"
		ln -sv ../sites-available/$name "$sitelink"
	;;
	disable-site)
		name=$2
		sitelink="$SITES_ENABLED_DIR/$name"

		if [ -L "$sitelink" ]; then
			rm -v "$sitelink"
		elif [ -e "$sitelink" ]; then
			die 4 "$sitelink is not a symlink!"
		fi
	;;
	enable-default-mods)
		for name in $DEFAULT_MODULES; do
			[ -L "$MODS_ENABLED_DIR/$name" ] && continue
			ln -sv ../mods-available/$name "$MODS_ENABLED_DIR/$name" || true
		done
	;;
	*)
		die 2 "unknown action: $1"
	;;
esac
