#! /bin/bash
sudo apt-get --purge remove autolauncher:armv7l -y
sudo apt-get --purge remove autolauncher:armhf -y
sudo apt-get --purge remove autolauncher:armh64 -y
sudo dpkg -i autolauncher_2.1.0_arm64.deb

# --- who gets autostart: prefer the user who used sudo, else the invoking user
TARGET_USER="${SUDO_USER:-$USER}"
if [ "$TARGET_USER" = "root" ] || [ -z "$TARGET_USER" ]; then
  echo "Set TARGET_USER: run as normal user (e.g. iar) with: sudo $0" >&2
  # optional: exit 1 or only install the .deb and skip the unit
else
  TARGET_HOME="$(getent passwd "$TARGET_USER" | cut -d: -f6)"
  TARGET_UID="$(id -u "$TARGET_USER")"
  RUNUSER_DIR="/run/user/$TARGET_UID"
  USER_UNIT_DIR="$TARGET_HOME/.config/systemd/user"
  UNIT="iar-autolauncher.service"

  install -d -m 0755 -o "$TARGET_USER" -g "$TARGET_USER" "$USER_UNIT_DIR" || true

  cat > "$USER_UNIT_DIR/$UNIT" << 'UNIT' 
[Unit]
Description=IaR Application Launcher
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=/bin/sh -c 'sleep 3; exec /usr/bin/autolauncher'
Restart=on-failure
RestartSec=3

[Install]
WantedBy=default.target
UNIT
  chown "$TARGET_USER:$TARGET_USER" "$USER_UNIT_DIR/$UNIT"

  # only if this user’s systemd --user is reachable (usually: logged in on the Pi desktop)
  if [ -S "$RUNUSER_DIR/bus" ]; then
    sudo -u "$TARGET_USER" \
      XDG_RUNTIME_DIR="$RUNUSER_DIR" \
      systemctl --user daemon-reload
    sudo -u "$TARGET_USER" \
      XDG_RUNTIME_DIR="$RUNUSER_DIR" \
      systemctl --user enable --now "$UNIT"
    echo "Autostart enabled for user $TARGET_USER"
  else
    echo "No user session for $TARGET_USER (no $RUNUSER_DIR/bus) — unit installed; after next login run:"
    echo "  systemctl --user --user=$TARGET_USER daemon-reload"  # actually wrong, see note below
    # Better message:
    echo "  Log in as $TARGET_USER, then: systemctl --user daemon-reload && systemctl --user enable --now $UNIT"
  fi
fi