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

# -----------------------------
# Defaults / flags
# -----------------------------
USER_INSTALL=1           # --user (default) or --system
MAKE_DESKTOP=1           # Desktop shortcut ON by default
APP_NAME="ScanXm"
APP_ID="scanxm"          # icon/desktop id (lowercase)
DESKTOP_FILENAME="${APP_ID}.desktop"

CURRENT_USER="$(id -un 2>/dev/null || echo "${LOGNAME:-unknown}")"

# -----------------------------
# Parse args
# -----------------------------
while [[ $# -gt 0 ]]; do
  case "$1" in
    --user) USER_INSTALL=1 ;;
    --system) USER_INSTALL=0 ;;
    --desktop) MAKE_DESKTOP=1 ;;
    --no-desktop) MAKE_DESKTOP=0 ;;
    -h|--help)
      cat <<EOF
Usage: $0 [--user|--system] [--desktop|--no-desktop]

--user        Install for current user (default)
--system      Install system-wide (requires root)
--desktop     Create a Desktop shortcut (default)
--no-desktop  Do not create a Desktop shortcut
EOF
      exit 0
      ;;
    *)
      echo "Unknown option: $1" >&2
      exit 1
      ;;
  esac
  shift
done

# -----------------------------
# Paths (source)
# -----------------------------
SRC_DIR="$(cd "$(dirname "$0")" && pwd)"

# Prefer wrapper ./ScanXm; fallback to raw ./bin/ScanXm
if [[ -x "$SRC_DIR/ScanXm" ]]; then
  BINARY_REAL="$SRC_DIR/ScanXm"
elif [[ -x "$SRC_DIR/bin/ScanXm" ]]; then
  BINARY_REAL="$SRC_DIR/bin/ScanXm"
else
  echo "ERROR: Could not find executable 'ScanXm' or 'bin/ScanXm' under: $SRC_DIR" >&2
  exit 1
fi

ICON_SRC="$SRC_DIR/share/icons/hicolor/256x256/apps/${APP_ID}.png"
DESKTOP_TEMPLATE="$SRC_DIR/share/applications/${APP_NAME}.desktop"

# -----------------------------
# Paths (user)
# -----------------------------
USER_BIN_LINK="$HOME/.local/bin/${APP_ID}"   # convenience symlink only
USER_APPS_DIR="$HOME/.local/share/applications"
USER_ICON_DIR="$HOME/.local/share/icons/hicolor/256x256/apps"
USER_HICOLOR_DIR="$HOME/.local/share/icons/hicolor"
if command -v xdg-user-dir >/dev/null 2>&1; then
  USER_DESKTOP_DIR="$(xdg-user-dir DESKTOP || true)"
fi
USER_DESKTOP_DIR="${USER_DESKTOP_DIR:-"$HOME/Desktop"}"

# -----------------------------
# Paths (system)
# -----------------------------
SYSTEM_BIN_LINK="/usr/local/bin/${APP_ID}"   # convenience symlink only
SYSTEM_APPS_DIR="/usr/share/applications"
SYSTEM_ICON_DIR="/usr/share/icons/hicolor/256x256/apps"
SYSTEM_HICOLOR_DIR="/usr/share/icons/hicolor"

# -----------------------------
# Helpers
# -----------------------------
have_cmd() { command -v "$1" >/dev/null 2>&1; }

refresh_caches_user() {
  have_cmd update-desktop-database && update-desktop-database "$USER_APPS_DIR" >/dev/null 2>&1 || true
  have_cmd gtk-update-icon-cache && gtk-update-icon-cache -f "$USER_HICOLOR_DIR" >/dev/null 2>&1 || true
  have_cmd xdg-desktop-menu && xdg-desktop-menu forceupdate >/dev/null 2>&1 || true
}

refresh_caches_system() {
  have_cmd update-desktop-database && update-desktop-database "$SYSTEM_APPS_DIR" >/dev/null 2>&1 || true
  have_cmd gtk-update-icon-cache && gtk-update-icon-cache -f "$SYSTEM_HICOLOR_DIR" >/dev/null 2>&1 || true
  have_cmd xdg-desktop-menu && xdg-desktop-menu forceupdate >/dev/null 2>&1 || true
}

write_desktop_file_inplace() {
  local dst="$1"
  local exec_path="$2"   # REAL path inside extracted folder
  local work_dir="$3"    # Path= (working directory)
  local icon_value="$4"  # theme icon name OR absolute icon path

  if [[ -f "$DESKTOP_TEMPLATE" ]]; then
    install -Dm0644 "$DESKTOP_TEMPLATE" "$dst"
    # Normalize / override critical fields
    sed -i \
      -e "s|^Exec=.*|Exec=${exec_path}|g" \
      -e "s|^Icon=.*|Icon=${icon_value}|g" \
      -e "s|^Name=.*|Name=${APP_NAME}|g" \
      -e "s|^Type=.*|Type=Application|g" \
      "$dst"
    # Ensure or append Path= (working dir)
    if grep -qE '^Path=' "$dst"; then
      sed -i -e "s|^Path=.*|Path=${work_dir}|g" "$dst"
    else
      printf '\nPath=%s\n' "$work_dir" >> "$dst"
    fi
  else
    mkdir -p "$(dirname "$dst")"
    cat >"$dst" <<EOF
[Desktop Entry]
Type=Application
Name=${APP_NAME}
Comment=Medical Image Visualization, Annotation and Segmentation Software
Exec=${exec_path}
Path=${work_dir}
Icon=${icon_value}
Terminal=false
Categories=Science;Graphics;Medical;
EOF
    chmod 0644 "$dst"
  fi
}

install_user() {
  echo "[*] Installing for user: ${CURRENT_USER}"

  # Optional CLI convenience symlink (doesn't affect launcher)
  mkdir -p "$(dirname "$USER_BIN_LINK")"
  ln -sf "$BINARY_REAL" "$USER_BIN_LINK"

  # Install icon first and prefer absolute icon path in the .desktop file.
  local icon_value="$APP_ID"
  if [[ -f "$ICON_SRC" ]]; then
    mkdir -p "$USER_ICON_DIR"
    install -m0644 "$ICON_SRC" "$USER_ICON_DIR/${APP_ID}.png"
    icon_value="$USER_ICON_DIR/${APP_ID}.png"
  fi

  # Desktop entry points to REAL path and runs from SRC_DIR
  local desktop_dst="$USER_APPS_DIR/${DESKTOP_FILENAME}"
  mkdir -p "$USER_APPS_DIR"
  write_desktop_file_inplace "$desktop_dst" "$BINARY_REAL" "$SRC_DIR" "$icon_value"

  # Optional Desktop shortcut (.desktop on the Desktop folder)
  if [[ "$MAKE_DESKTOP" -eq 1 ]]; then
    mkdir -p "$USER_DESKTOP_DIR"
    cp -f "$desktop_dst" "$USER_DESKTOP_DIR/${APP_NAME}.desktop"
    chmod +x "$USER_DESKTOP_DIR/${APP_NAME}.desktop"
  fi

  refresh_caches_user

  echo "[+] Installed launcher: $desktop_dst"
  echo "[+] (Optional) CLI symlink: $USER_BIN_LINK -> $BINARY_REAL"
  if [[ "$MAKE_DESKTOP" -eq 1 ]]; then
    echo "[+] Desktop shortcut: $USER_DESKTOP_DIR/${APP_NAME}.desktop"
  fi
}

install_system() {
  if [[ "$(id -u)" -ne 0 ]]; then
    echo "ERROR: --system install requires root. Re-run with sudo." >&2
    exit 1
  fi

  echo "[*] Installing system-wide"

  # Optional CLI convenience symlink (doesn't affect launcher)
  ln -sf "$BINARY_REAL" "$SYSTEM_BIN_LINK"

  # Install icon first and prefer absolute icon path in the .desktop file.
  local icon_value="$APP_ID"
  if [[ -f "$ICON_SRC" ]]; then
    mkdir -p "$SYSTEM_ICON_DIR"
    install -m0644 "$ICON_SRC" "$SYSTEM_ICON_DIR/${APP_ID}.png"
    icon_value="$SYSTEM_ICON_DIR/${APP_ID}.png"
  fi

  # Desktop entry into /usr/share/applications, pointing to REAL path
  local desktop_dst="$SYSTEM_APPS_DIR/${DESKTOP_FILENAME}"
  write_desktop_file_inplace "$desktop_dst" "$BINARY_REAL" "$SRC_DIR" "$icon_value"

  refresh_caches_system

  echo "[+] Installed launcher: $desktop_dst"
  echo "[+] (Optional) CLI symlink: $SYSTEM_BIN_LINK -> $BINARY_REAL"
  if [[ "$MAKE_DESKTOP" -eq 1 ]]; then
    echo "[i] Note: system install does not create per-user Desktop shortcuts."
    echo "    Each user can run: \"$0 --user --desktop\" to add their own shortcut."
  fi
}

# -----------------------------
# Do it
# -----------------------------
if [[ "$USER_INSTALL" -eq 1 ]]; then
  install_user
else
  install_system
fi
