#!/bin/sh -e
#
# 2022 Joachim Desroches (joachim.desroches@epfl.ch)
#
# This file is part of cdist.
#
# cdist is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cdist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cdist. If not, see <http://www.gnu.org/licenses/>.
#

os=$(cat "${__global:?}/explorer/os")

case "$os" in
'debian' | 'ubuntu' | 'archlinux')
	:
	;;
*)
	printf "Your operating system (%s) is currently not supported by systemd-network\n" "$os" >&2
	printf "Please contribute an implementation for it if you can.\n" >&2
	exit 1
	;;
esac

# XXX: Please keep the option parsing organized in order per-section, with
# sections in the same order as they are in the manpage. This will make hacking
# and maintaining this type much easier.

mkdir "${__object:?}/files"
output_file="${__object:?}/files/${__object_id:?}.network"

cat << EOF > "$output_file"
# This file is managed by cdist. Do not edit by hand!
EOF

# Match section
# Ensure section is needed, OR existence of optional params.
if [ -f "${__object:?}/parameter/match-name" ];
then
	printf "\n[Match]\n" >> "$output_file"

	if [ -f "${__object:?}/parameter/match-name" ];
	then
		sed -e 's/^/Name=/' \
			"${__object:?}/parameter/match-name" >> "$output_file"
	fi
fi

# Network section
# Ensure section is needed, OR existence of optional params.
if [ -f "${__object:?}/parameter/description" ];
then
	printf "\n[Network]\n" >> "$output_file"

	if [ -f "${__object:?}/parameter/description" ];
	then
		sed -e 's/^/Description=/' \
			"${__object:?}/parameter/description" >> "$output_file"
	fi
fi

# IPv6AcceptRA section
# Ensure section is needed, OR existence of optional params.
if [ -f "${__object:?}/parameter/ipv6ra-usedomains" ];
then
	printf "\n[IPv6AcceptRA]\n" >> "$output_file"

	if [ -f "${__object:?}/parameter/ipv6ra-usedomains" ];
	then
		printf "UseDomains=True\n" >> "$output_file"
	fi
	
fi

__file "/etc/systemd/network/${__object_id:?}.network" \
	--source "$output_file" \
	--mode 0644
