#!/bin/bash

# Generate systemd files for running a systemd-based service
# in a VRF. Generator creates instance templates for services
# that do not have them and creates unit overrides to prepend
# 'vrf exec %I' to all Exec lines.

PROG=systemd-vrf-generator

# config file noting services that might run in a VRF
VRFCONF=/etc/vrf/systemd.conf

# where to find systemd service files
SYSTEMD_SVC=/lib/systemd/system/

# where to write the instance service files created
# by this generator
SYSTEMD_ETC=/etc/systemd/system/

VRFGEN_NOTE="created by vrf generator"

do_cleanup()
{
	local dest=${1}
	local file

	grep -d skip -l "${VRFGEN_NOTE}" ${SYSTEMD_ETC}/*.service | \
	while read file
	do
		/bin/rm -f ${file}
	done

	grep -r -l "${VRFGEN_NOTE}" ${dest} | \
	while read file
	do
		/bin/rm -f ${file}
	done
}

create_instance()
{
	local dest=${1}
        local s=${2}

        local file=${SYSTEMD_SVC}/${s}.service
        local ifile=${SYSTEMD_SVC}/${s}@.service
        local vrffile=${SYSTEMD_ETC}/${s}@.service
	local vrfunit=${dest}/${s}@.service.d

	# no service file, nothing to do -- maybe the package
	# has not been installed yet
	[ ! -e ${file} -a ! -e ${ifile} ] && return

	# if service brings along its own instance file no
	# need to create one
	if [ -e ${ifile} ]; then
		file=${ifile}
	else
		echo "# ${VRFGEN_NOTE}" > ${vrffile}
		cat ${file} >> ${vrffile}

		ifile=${vrffile}
	fi

	mkdir -p ${vrfunit}
	(
	echo "# ${VRFGEN_NOTE}"
	echo "[Unit]"
	echo "SourcePath=${file}"
	echo
	echo "[Service]"
        awk -F'=' '$1 ~ /^Exec/ {
                print $1 "="
                print $1 "=/usr/bin/vrf task exec %I " $2
        }' ${ifile}
	) > ${vrfunit}/vrf.conf
}

# take the normal-dir for writing our temp files
dest=${1}

# remove old files
do_cleanup ${1}

[ ! -e ${VRFCONF} ] && exit 0

while read service
do
	create_instance ${dest} ${service}
done < ${VRFCONF}

exit 0
