#!/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/>.
#

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

# Optional parameters
BITS=
if [ -f "${__object:?}/parameter/bits" ]; then
	BITS="-b $(cat "${__object:?}/parameter/bits")"
fi

# Boolean parameters
SUBDOMAINS=
if [ -f "${__object:?}/parameter/no-subdomains" ]; then
	SUBDOMAINS='--nosubdomains'
fi

RESTRICTED='--restrict'
if [ -f "${__object:?}/parameters/unrestricted" ]; then
	RESTRICTED=
fi

user="$(cat "${__object:?}/user")"
group="$(cat "${__object:?}/group")"

KEY_STATE="$(cut -f 1 "${__object:?}/explorer/key-state")"
KEY_LOCATION="$(cut -f 2- "${__object:?}/explorer/key-state")"

if [ "${KEY_STATE:?}" = "absent" ]; then
	# opendkim-genkey(8) does not allow specifying the file name.
	# To err on the safe side (and avoid potentially killing other keys)
	# we operate on a temporary directory first, then move the resulting key
	cat <<-EOF
	tmp_dir="\$(mktemp -d cdist-dkim.XXXXXXXXXXX)"
	opendkim-genkey $BITS --domain=${DOMAIN:?} --directory=\${tmp_dir:?} $RESTRICTED --selector=${SELECTOR:?} $SUBDOMAINS
	# Relocate and ensure permissions
	mv "\${tmp_dir:?}/${SELECTOR:?}.private" '${KEY_LOCATION:?}'
	chown ${user}:${group} '${KEY_LOCATION}'
	chmod 0600 '${KEY_LOCATION}'
	# This is usually generated, if it weren't we do not want to fail
	mv "\${tmp_dir:?}/${SELECTOR:?}.txt" '${KEY_LOCATION%.private}.txt' || true
	chown ${user}:${group} '${KEY_LOCATION%.private}.txt' || true
	# Cleanup after ourselves
	rmdir "\${tmp_dir:?}" || true
	EOF
fi
