#!/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:?}/parameter/domain")"
SELECTOR="$(cat "${__object:?}/parameter/selector")"

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

DIRECTORY="/var/db/dkim/"
if [ -f "${__object:?}/parameter/directory" ]; then
	DIRECTORY="$(cat "${__object:?}/parameter/directory")"
fi

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

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

if ! [ -f "${DIRECTORY}${SELECTOR}.private" ]; then
	echo "opendkim-genkey $BITS --domain=$DOMAIN --directory=$DIRECTORY $RESTRICTED --selector=$SELECTOR $SUBDOMAINS"
	echo "chown opendkim:opendkim ${DIRECTORY}${SELECTOR}.private"
fi
