#!/bin/bash
# Under systemd, davmail starts up with the DynamicUser _davmail and reduced
# privileges. And usualy, the administrator wants to have restricted read
# permissions for private SSL key files.
# This creates problems for reading private SSL keys because the keys file must be
# readable by the _davmail user. As this user is created by systemd on service start,
# restricted permissions cannot be put in place before the daemon starts.
# Called upon before the daemon starts, this script solves this by copying the keys
# file (if it exists) in a restricted directory and chmod'ing it into the runtime
# user. If the administrator has not created any keyfile, the previously copied
# keyfile, if any, is deleted.

set -e

user=_davmail

function cpchown {
    /bin/cp -u "$1" "$2"
    /bin/chown "$user:$user" "$2"
}

stateDirectory=/var/lib/davmail

keystoreFile=$(/bin/readlink -f /etc/davmail/keystoreFile)
if [ -f "$keystoreFile" ]; then
    cpchown "$keystoreFile" "$stateDirectory/keystoreFile"
else
    /bin/rm -f "$stateDirectory/keystoreFile"
fi
