#!/bin/sh -e
#
# 2021 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")

CFG_DIR="/etc/opendkim/"
KEYS_DIR="/var/db/dkim/"
user="opendkim"
group="opendkim"
case "$os" in
'alpine')
	:
;;
'debian')
	CFG_DIR="/etc/dkimkeys/"
	KEYS_DIR="/etc/dkimkeys/"
;;
'freebsd')
	CFG_DIR="/usr/local/etc/mail"
	user="mailnull"
	group="mailnull"
;;
*)
	cat <<- EOF >&2
	__opendkim_genkey does not support $os (yet). Exiting.
	EOF
	exit 1
;;
esac
# Persist user and group for gencode-remote
printf '%s' "${user}" > "${__object:?}/user"
printf '%s' "${group}" > "${__object:?}/group"

SELECTOR="$(cat "${__object:?}/parameter/selector")"
DOMAIN="$(cat "${__object:?}/parameter/domain")"

if [ -f "${__object:?}/parameter/directory" ];
then
	# Be forgiving about a lack of trailing slash
	KEYS_DIR="$(sed -E 's!([^/])$!\1/!' < "${__object:?}/parameter/directory")"
fi

SIGKEY="${DOMAIN:?}"
if [ -f "${__object:?}/parameter/sigkey" ];
then
	SIGKEY="$(cat "${__object:?}/parameter/sigkey")"
fi

# Ensure the key-container directory exists with the proper permissions
__directory "${KEYS_DIR}" \
	--mode 0750 \
	--owner "${user}" --group "${group}"

# OS-specific code
case "$os" in
'alpine')
	__package opendkim-utils
;;
'debian')
	__package opendkim-tools
;;
esac

key_table="${CFG_DIR}/KeyTable"
signing_table="${CFG_DIR}/SigningTable"

__line "line-key-${__object_id:?}" \
	--file "${key_table}" \
	--line "${SELECTOR:?}._domainkey.${DOMAIN:?} ${DOMAIN:?}:${SELECTOR:?}:${KEYS_DIR:?}${SELECTOR:?}.private"

__line "line-sig-${__object_id:?}" \
	--file "${signing_table}" \
	--line "${SIGKEY:?} ${SELECTOR:?}._domainkey.${DOMAIN:?}"
