#!/bin/sh

# This systemd generator creates dependency symlinks that make all
# avregd profiles with "auto" be started/stopped/reloaded
# when avreg.service is started/stopped/reloaded.

set -eu

confdir="$1/avreg.service.d"
wantdir="$1/avreg.service.wants"

PROFILESDIR='/etc/avreg/profiles'
AVREGD_PROFILES=$(cd $PROFILESDIR 2>/dev/null && find -type f -regex '\./[A-Za-z0-9][A-Za-z0-9_\.:\-]+' -exec basename {} \; | sort)

if [ -z "$AVREGD_PROFILES" ]; then
   [ -d "$wantdir" ] && rm -fR "$wantdir"
   [ -d "$confdir" ] || mkdir -p "$confdir"
   cat > "${confdir}/avregd@.service.conf" <<_EOF_
# Automatically generated by avregd-generator
# systemd service template for fake single profile of avregd.

[Unit]
Description=AVReg daemon
ConditionPathExists=/etc/avreg/avreg.conf
Requires=avreg-supervisor.service
PartOf=avreg.service
ReloadPropagatedFrom=avreg.service
Wants=network-online.target mysql.service postgresql.service
After=network-online.target remote-fs.target nss-lookup.target time-sync.target avreg-supervisor.service mysql.service postgresql.service rc-local.service

[Service]
Type=forking
EnvironmentFile=-/etc/default/avreg
ExecStart=
ExecStart=/usr/sbin/avregd \$AVREGD_ARGS
ExecReload=
ExecReload=/bin/kill -HUP \$MAINPID
PIDFile=/run/avreg/avregd.pid
SyslogIdentifier=avregd
Restart=on-abnormal
RestartSec=2s


[Install]
WantedBy=multi-user.target
_EOF_

 else
   [ -d "$confdir" ] && rm -fR "$confdir"
   [ -d "$wantdir" ] || mkdir -p "$wantdir"
   for p in $AVREGD_PROFILES; do
      ln -s "/lib/systemd/system/avregd@.service" "${wantdir}/avregd@${p}.service"
   done
fi

exit 0
