#!/usr/bin/bash
#
# dmal-call-hook
# this hook is called as root and will call setup/cleanup hooks

set -o errexit
set -o pipefail
set -o nounset
set -o errtrace

function cleanup() {
    trap - ERR
    trap - EXIT
}

# shellcheck disable=SC2329,SC2317
function err_exit_trap() {
    local _status=$?
    local _traptype="$1"

    cleanup

    echo "${FUNCNAME[0]-?}: unexpected exit/error" \
         "near '$BASH_COMMAND', status=$_status, trap=$_traptype"
    exit 1
}

trap 'err_exit_trap "ERR"' ERR
trap 'err_exit_trap "EXIT"' EXIT

exec > \
     >(systemd-cat -t dmal-call-hooks -p info) \
     2> >(systemd-cat -t dmal-call-hooks -p err)

function fatal() {
    echo "FATAL ERROR: $*" >&2
    cleanup
    exit 1
}

# default values
DMAL_DM_BIN=/usr/sbin/lightdm
DMAL_HOOK_DIR=/etc/dmal/hooks
DMAL_RUN_DIR=/var/run/dmal
DMAL_EXIT_ON_ERROR=
DMAL_SESSIONS_DIR=

if [ -f /etc/default/dmal ]
then
    # shellcheck disable=SC1091
    source /etc/default/dmal || fatal "failed to source /etc/default/dmal"
else
    echo "WARNING: /etc/default/dmal not found, using hardcoded values"
fi

(( $# == 1 )) || fatal "called with $# args instead of 1"

case "$1" in
    setup|cleanup) DMAL_HOOK_SUBDIR="$DMAL_HOOK_DIR/session-$1.d";;
    *) fatal "called with illegal arg: $1"
esac

[ -n "${USER-}" ] || {
    echo "\$USER was undefined, giving up"
    cleanup
    exit 0
}

echo "called for $USER (id=$(id))"

if [ -d "$DMAL_HOOK_SUBDIR" ]
then
    shopt -s nullglob
    for hook in "$DMAL_HOOK_SUBDIR"/*
    do
        echo "calling $1 hook: $hook"
        if "$hook" "$USER" \
                   > >(systemd-cat -t "dmal-$1-hook:${hook##*/}" -p info) \
                   2> >(systemd-cat -t "dmal-$1-hook:${hook##*/}" -p err)
        then
            echo "$1 hook $hook finished successfully"
        else
            case "$1" in
                setup)
                    echo "$1 hook $hook failed with $? - aborting setup"
                    cleanup
                    exit 1
                    ;;
                cleanup)
                    echo "$1 hook $hook failed with $? - continuing cleanup"
                    ;;
            esac
        fi
    done
else
    echo "hook subdir ($DMAL_HOOK_SUBDIR) not found, not calling any hooks"
fi

cleanup
exit 0
