#!/bin/sh
# Runs after the package is unpacked. We:
#   1. create the system user/group _logtail (idempotent);
#   2. on first install, render /etc/default/nginx-logtail from the template;
#   3. reload systemd.
#
# We deliberately do NOT enable or start the units — some hosts run only the
# collector, some only the aggregator, some run both with the frontend, some
# run neither. The operator is expected to run:
#
#   systemctl enable --now nginx-logtail-collector.service
#   systemctl enable --now nginx-logtail-aggregator.service
#   systemctl enable --now nginx-logtail-frontend.service
#
# on the hosts that should run each service.
set -e

TEMPLATE=/usr/share/nginx-logtail/default.template
TARGET=/etc/default/nginx-logtail

if [ "$1" = configure ]; then
    if ! getent group _logtail >/dev/null; then
        addgroup --system _logtail
    fi
    if ! getent passwd _logtail >/dev/null; then
        adduser --system --ingroup _logtail \
            --no-create-home --home /nonexistent \
            --shell /usr/sbin/nologin \
            --gecos "nginx-logtail" \
            _logtail
    fi

    # First install: $2 is empty. Render the template with the current
    # short hostname, but never clobber an existing file (in case the
    # operator dropped one in manually before installing).
    if [ -z "$2" ] && [ ! -e "$TARGET" ]; then
        HOSTNAME_SHORT="$(hostname -s 2>/dev/null || hostname 2>/dev/null || echo localhost)"
        # Use a delimiter unlikely to appear in hostnames.
        sed "s|%HOSTNAME%|${HOSTNAME_SHORT}|g" "$TEMPLATE" > "$TARGET"
        chmod 0644 "$TARGET"
        chown root:root "$TARGET"
    fi

    if [ -d /run/systemd/system ]; then
        systemctl daemon-reload || true
    fi
fi

#DEBHELPER#
exit 0
