#!/bin/sh -e

os=$( "${__explorer:?}/os" )

case "$os" in
'debian')
	DIRECTORY="/etc/dkimkeys/"
;;
*)
	DIRECTORY="/var/db/dkim/"
;;
esac

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

KEY_ID="$(echo "${__object_id:?)}" | tr '/' '_')"
DEFAULT_PATH="${DIRECTORY:?}${KEY_ID:?}.private"
if [ -s "${DEFAULT_PATH}" ]; then
	# This is the main location for the key
	FOUND_PATH="${DEFAULT_PATH}"
else
	# This is a backwards-compatible location for the key
	# Keys generated post March 2022 should not land here
	if [ -f "${__object:?}/parameter/selector" ]; then
		SELECTOR="$(cat "${__object:?}/parameter/selector")"
		if [ -s "${DIRECTORY}${SELECTOR:?}.private" ]; then
			FOUND_PATH="${DIRECTORY}${SELECTOR:?}.private"
		fi
	fi
fi

if [ -n "${FOUND_PATH}" ]; then
	printf "present\t%s" "${FOUND_PATH}"
else
	# We didn't find the key
	# We pass the default path here, to easen logic in the rest of the type
	printf "absent\t%s" "${DEFAULT_PATH}"
fi
