#!/bin/bash
# =============================================================================
#  auxinux-virtua postinst
#  $1 = configure (fresh install or upgrade)
#  $2 = <previous-version> when upgrading, empty on first install
#
#  We must NOT run apt-get here (the dpkg lock is held by the parent apt). So we
#  pick the install mode and kick off the provisioning systemd unit non-blocking;
#  it runs install.sh once the apt transaction releases the lock.
# =============================================================================
set -e

INSTALL_DIR="/opt/auxinux-virtua"
SETUP_UNIT="auxinux-virtua-setup.service"

case "$1" in
  configure)
    # Make bundled scripts executable (dpkg preserves modes, but be safe).
    chmod 0755 "${INSTALL_DIR}/packaging/deb/run-setup.sh" 2>/dev/null || true
    find "${INSTALL_DIR}/INSTALL" -name "*.sh" -exec chmod 0755 {} \; 2>/dev/null || true

    # First install (no previous version in $2) → full install; otherwise update.
    if [ -z "$2" ]; then
      MODE="install"
    else
      MODE="update"
    fi

    # Pass the mode to the setup unit via a runtime env file.
    mkdir -p /run
    echo "AUXINUX_VIRTUA_SETUP_MODE=${MODE}" > /run/auxinux-virtua-setup.env

    # Reload units (the service file ships in /lib/systemd/system) and enable it.
    if [ -d /run/systemd/system ]; then
      systemctl daemon-reload || true
      systemctl enable "${SETUP_UNIT}" >/dev/null 2>&1 || true
      # --no-block: return immediately so the apt transaction can finish and
      # release the dpkg lock; the unit waits for the lock then runs install.sh.
      systemctl start --no-block "${SETUP_UNIT}" || true
      echo "auxinux-virtua: provisioning (${MODE}) started in background."
      echo "  Follow it with:  journalctl -fu auxinux-virtua-setup"
    else
      echo "auxinux-virtua: systemd not detected — run manually:"
      echo "  AUXINUX_VIRTUA_SETUP_MODE=${MODE} ${INSTALL_DIR}/packaging/deb/run-setup.sh"
    fi
    ;;
  abort-upgrade|abort-remove|abort-deconfigure)
    ;;
esac

exit 0
