#!/usr/bin/env bash
set -euo pipefail

PKG_NAME="stillos-session"

usage() {
  echo "Usage: $0 [--remove-only] [--user-systemd-dir DIR]" >&2
}

REMOVE_ONLY=0
USER_SYSTEMD_DIR="/usr/lib/systemd/user"

while [[ ${1:-} ]]; do
  case "$1" in
    --remove-only)
      REMOVE_ONLY=1
      shift
      ;;
    --user-systemd-dir)
      USER_SYSTEMD_DIR="$2"
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage
      exit 1
      ;;
  esac
done

remove_previous() {
  echo "Removing any previous installation..."
  sudo rm -f \
    /usr/share/wayland-sessions/stillos.desktop \
    /usr/share/gnome-session/sessions/stillos.session \
    "$USER_SYSTEMD_DIR"/gnome-session@stillos.target.d/stillos.session.conf \
    /usr/share/glib-2.0/schemas/10_stillos.gschema.override \
    /usr/share/glib-2.0/schemas/zz_stillos-fonts.gschema.override \
    "$USER_SYSTEMD_DIR"/stillos-shortcuts.service \
    /usr/libexec/stillos-shortcuts-init \
    /usr/share/gnome-shell/modes/stillos.json || true

  # Remove empty directories quietly
  sudo rmdir "$USER_SYSTEMD_DIR"/gnome-session@stillos.target.d 2>/dev/null || true
  sudo rmdir /usr/share/gnome-session/sessions 2>/dev/null || true
  sudo rmdir /usr/share/gnome-shell/modes 2>/dev/null || true

  # Recompile schemas if tool exists
  if command -v glib-compile-schemas >/dev/null 2>&1; then
    sudo glib-compile-schemas /usr/share/glib-2.0/schemas || true
  fi
}

install_files() {
  echo "Installing files..."
  sudo install -D -m 0644 stillos.desktop /usr/share/wayland-sessions/stillos.desktop
  sudo install -D -m 0644 stillos.session /usr/share/gnome-session/sessions/stillos.session
  sudo install -D -m 0644 stillos.session.conf "$USER_SYSTEMD_DIR"/gnome-session@stillos.target.d/stillos.session.conf
  sudo install -D -m 0644 stillos-shortcuts.service "$USER_SYSTEMD_DIR"/stillos-shortcuts.service
  sudo install -D -m 0755 stillos-shortcuts-init /usr/libexec/stillos-shortcuts-init
  sudo install -D -m 0644 10_stillos.gschema.override /usr/share/glib-2.0/schemas/10_stillos.gschema.override
  sudo install -D -m 0644 zz_stillos-fonts.gschema.override /usr/share/glib-2.0/schemas/zz_stillos-fonts.gschema.override
  sudo install -D -m 0644 stillos.json /usr/share/gnome-shell/modes/stillos.json

  if command -v glib-compile-schemas >/dev/null 2>&1; then
    sudo glib-compile-schemas /usr/share/glib-2.0/schemas || true
  fi
}

remove_previous

if [[ "$REMOVE_ONLY" -eq 1 ]]; then
  echo "Remove-only mode requested. Exiting after cleanup."
  exit 0
fi

install_files
echo "Installation complete. Select 'stillOS Desktop' on login."
