#!/bin/sh

set -eu

setup_user () {
    # Sets up the stork-agent user and its home directory. Creates folders for
    # storing certs and agent token, they should be available to owner ie.
    # stork-agent user.
    home_dir=/var/lib/stork-agent
    mkdir -p "${home_dir}/certs"
    mkdir -p "${home_dir}/tokens"
    chmod 700 "${home_dir}/certs"
    chmod 700 "${home_dir}/tokens"

    # Add stork-agent user.
    if ! getent passwd stork-agent > /dev/null; then
        useradd --system --home-dir "${home_dir}" stork-agent >/dev/null
    fi

    # Add stork-agent user to bind so it can read its config files.
    if getent group bind > /dev/null; then
        usermod -aG bind stork-agent
    fi

    # Add stork-agent user to kea so it can read its config files.
    if getent group _kea > /dev/null; then
        usermod -aG _kea stork-agent
    fi

    # Change ownership of all folders and files in home dir to stork-agent user.
    chown -R stork-agent "${home_dir}"
}

after_install () {
    setup_user
}

after_upgrade () {
    # Prior Stork 1.16.0 the update case was not specifically handled. The
    # postrm script deleted the user and the postinst recreated it.
    # The user is preserved during the upgrade if the version is 1.16.0 or
    # higher for the older versions, the user must be recreated.
    setup_user

    # Check if the systemd is available.
    has_active_systemd=0
    if command -v systemctl > /dev/null; then
        status=$(systemctl is-system-running || true)
        if [ "${status}" = "running" ] || [ "${status}" = "degraded" ] || [ "${status}" = "maintenance" ]; then
            has_active_systemd=1
        fi
    fi

    # Restart the systemd service if needed.
    if [ $has_active_systemd -eq 1 ]; then
        is_active_service=$(systemctl is-active isc-stork-agent || true)
        if [ "${is_active_service}" = "active" ]; then
            systemctl restart isc-stork-agent
        fi
    fi
}


if [ "${1}" = "abort-remove" ] || { [ "${1}" = "configure" ] && [ -z "${2}" ]; }
then
    # "after install" here.
    # "abort-remove" happens when the pre-removal script failed.
    #   In that case, this script, which should be idempotent, is run
    #   to ensure a clean roll-back of the removal.
    after_install
elif [ "${1}" = "configure" ] && [ -n "${2}" ]
then
    # "after upgrade" here.
    # NOTE: This slot is also used when deb packages are removed,
    # but their config files aren't, but a newer version of the
    # package is installed later, called "Config-Files" state.
    # Basically, that still looks a _lot_ like an upgrade to me.
    after_upgrade "${2}"
elif echo "${1}" | grep -E -q "(abort|fail)"
then
    echo "Failed to install before the post-installation script was run." >&2
    exit 1
fi
