#!/bin/bash
# postinst for smartbotic-automation
set -e

SM_USER="smartbotic-automation"
SM_GROUP="smartbotic-automation"
SM_HOME="/home/smartbotic-automation"
SERVICES="smartbotic-automation-webserver smartbotic-automation-runner"

case "$1" in
    configure)
        # System group + user (idempotent)
        if ! getent group "$SM_GROUP" >/dev/null 2>&1; then
            addgroup --system "$SM_GROUP"
        fi
        if ! getent passwd "$SM_USER" >/dev/null 2>&1; then
            adduser --system --ingroup "$SM_GROUP" --home "$SM_HOME" \
                --shell /usr/sbin/nologin \
                --gecos "SmartBotic Automation Service User" "$SM_USER"
        fi

        install -d -o "$SM_USER" -g "$SM_GROUP" -m 0750 "$SM_HOME"
        install -d -o "$SM_USER" -g "$SM_GROUP" -m 0750 /var/lib/smartbotic-automation
        install -d -o "$SM_USER" -g "$SM_GROUP" -m 0750 /var/log/smartbotic-automation
        install -d -o root      -g "$SM_GROUP" -m 0750 /etc/smartbotic-automation

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

        if [ -z "$2" ]; then
            # First install: enable but do NOT start (admin must configure
            # database_address first; the upstream DB port is deployment-specific).
            for svc in $SERVICES; do
                deb-systemd-helper enable "$svc.service" >/dev/null || true
            done
            echo
            echo "smartbotic-automation: services are enabled but not started."
            echo "  WARNING: webserver.json contains placeholder values for jwt_secret and"
            echo "           credentials.master_key. Replace 'CHANGE_ME_BEFORE_PRODUCTION'"
            echo "           with strong unique secrets before starting the service in production."
            echo
            echo "  Configuration steps:"
            echo "  1. Edit /etc/smartbotic-automation/webserver.json (set database_address, jwt_secret, credentials.master_key)"
            echo "  2. Edit /etc/smartbotic-automation/runner.json (set database_address)"
            echo "  3. systemctl start smartbotic-automation-webserver smartbotic-automation-runner"
            echo
        else
            # Upgrade path: try-restart any active units
            for svc in $SERVICES; do
                deb-systemd-invoke try-restart "$svc.service" >/dev/null 2>&1 || true
            done
        fi
        ;;
esac

exit 0
