#!/bin/sh
set -eu
if [ "$1" = configure ]; then
  if ! getent group sikano-print >/dev/null; then addgroup --system sikano-print; fi
  if ! getent passwd sikano-print >/dev/null; then adduser --system --ingroup sikano-print --home /var/lib/sikano-print --no-create-home --disabled-login sikano-print; fi
  adduser sikano-print lp >/dev/null
  adduser sikano-print lpadmin >/dev/null
  install -d -o sikano-print -g sikano-print -m 0700 /var/lib/sikano-print
  install -d -o root -g root -m 0755 /etc/sikano-print
  install -d -o root -g root -m 0700 /var/lib/sikano-print-updater
  # The fixed helper installs no active rule on generic/Lite systems. Image
  # builds install Desktop files without reloading or triggering host devices.
  /usr/bin/timeout --kill-after=2s 90s /usr/bin/node /usr/lib/sikano-print/desktop/udisks-setup.mjs
  /usr/bin/node /usr/lib/sikano-print/desktop/firstboot.mjs --install-autostart
  # Fixed tty1 dimensions bypass systemd 257's blocking pre-exec DSR query.
  # The helper acts only on a protected Sikano Desktop ab-v1 marker.
  /usr/bin/node /usr/lib/sikano-print/desktop/tty-setup.mjs
  # Only A/B appliances order BlueZ behind their existing shared-data mount.
  # This writes a fixed drop-in; no pairing, key access or service restart.
  /usr/bin/node /usr/lib/sikano-print/ota-system/bluetooth-state.mjs --install
  if [ -z "${SIKANO_IMAGE_BUILD:-}" ] && [ "${SIKANO_PRINT_OTA:-}" = 1 ] && [ -d /run/systemd/system ]; then
    # Fixed, one-shot private-0.3.0 repair only. Never replay cloud-init or seed
    # commands, and never let an unavailable SSH repair block package configure.
    if ! /usr/bin/timeout --kill-after=2s 30s /usr/bin/node /usr/lib/sikano-print/firstboot/repair-ssh.mjs; then
      printf 'Sikano SSH-Ersteinrichtung: Zeitlimit oder Fehler; sicher übersprungen.\n' >&2
    fi
  fi
  if [ -d /run/systemd/system ]; then
    systemctl daemon-reload
    systemctl enable sikano-print.service sikano-print-updater.service sikano-print-network.service sikano-print-airprint.service sikano-print-bluetooth.service
    # Start the fixed local helper also during OTA. It has no cloud installer
    # role and must not restart the updater process that is running dpkg.
    if [ -z "${SIKANO_IMAGE_BUILD:-}" ]; then
      systemctl restart sikano-print-network.service
      systemctl restart sikano-print-airprint.service sikano-print-bluetooth.service
    fi
    # The installer is itself running below the updater during OTA. Restarting
    # that service here would kill dpkg and interrupt the durable transaction.
    if [ -z "${SIKANO_IMAGE_BUILD:-}" ] && [ -z "${SIKANO_PRINT_OTA:-}" ]; then
      systemctl restart sikano-print.service
      systemctl try-restart sikano-print-updater.service
      if [ -f /etc/sikano-print/update-public.pem ]; then systemctl start sikano-print-updater.service; fi
    fi
  fi
  printf '\nSikano Print ist installiert.\nEinrichtung im Browser: http://%s.local:8765\n\n' "$(hostname)"
fi
