#!/bin/sh
set -e

VSMTP_USER="vsmtp"

DPKG_NAME="vsmtp"
DPKG_VER=`dpkg -s $DPKG_NAME | sed -n 's/^Version: //p'`

CONF_DIR="/etc/vsmtp/"
CONF_FILE=${CONF_DIR}"vsmtp.toml"

LOG_DIR="/var/log/vsmtp/"
SPOOL_DIR="/var/spool/vsmtp/"

add_user() {
    if id ${VSMTP_USER} > /dev/null 2>&1; then return; fi
    adduser --system --shell /usr/sbin/nologin --no-create-home \
    --group --disabled-password --disabled-login --no-create-home --home /noexistent ${VSMTP_USER}
}

# TOCHECK : Automatic directory creation w/ systemd
# https://www.freedesktop.org/software/systemd/man/systemd.exec.html
# but... "the innermost specified directories will be owned by the user
# and group specified in User= and Group=. If the specified directories
# already exist and their owning user or group do not match the configured
# ones, all files and directories below the specified directories as well
# as the directories themselves will have their file ownership recursively
# changed to match what is configured.
check_dir() {
    # vSMTP log directory
    if [ ! -d "${LOG_DIR}" ]; then
        mkdir ${LOG_DIR}
        chown ${VSMTP_USER}:${VSMTP_USER} ${LOG_DIR}
        chmod 755 ${LOG_DIR}
    fi
    # vSMTP spool directory
    if [ ! -d "${SPOOL_DIR}" ]; then
        mkdir ${SPOOL_DIR}
        chown ${VSMTP_USER}:${VSMTP_USER} ${SPOOL_DIR}
        chmod 755 ${SPOOL_DIR}
    fi
    # vSMTP data directory
    if [ ! -d "${CONF_DIR}" ]; then
        mkdir ${CONF_DIR}
        chown ${VSMTP_USER}:${VSMTP_USER} ${CONF_DIR}
        chmod 755 ${CONF_DIR}
    fi
}

check_toml() {
    if [ ! -f "${CONF_FILE}" ]; then
        echo "version_requirement = \">=${DPKG_VER}\"" > ${CONF_FILE}
        chown ${VSMTP_USER}:${VSMTP_USER} ${CONF_FILE}
        chmod 664 ${CONF_FILE}
    fi
}


case "$1" in
configure)
    add_user
    check_dir
    check_toml
    ;;
esac

#DEBHELPER#
