#!/usr/bin/env bash
# Install ScoreImmobilier Desktop for the current user (no root).
# Usage: ./install-linux.sh
#        ./install-linux.sh --uninstall
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
PREFIX="${PREFIX:-$HOME/.local}"
BIN_DIR="$PREFIX/bin"
APP_DIR="$PREFIX/share/applications"
ICON_DIR="$PREFIX/share/icons/hicolor/128x128/apps"
BIN_DST="$BIN_DIR/scoreimmobilier-desktop"
ICON_DST="$ICON_DIR/scoreimmobilier-desktop.png"
DESKTOP_DST="$APP_DIR/scoreimmobilier-desktop.desktop"

uninstall() {
  rm -f "$BIN_DST" "$ICON_DST" "$DESKTOP_DST"
  if command -v update-desktop-database >/dev/null 2>&1; then
    update-desktop-database "$APP_DIR" >/dev/null 2>&1 || true
  fi
  echo "Désinstallé (données conservées dans ~/.scoreimmobilier-desktop)"
  exit 0
}

if [[ "${1:-}" == "--uninstall" ]]; then
  uninstall
fi

BIN_SRC="$ROOT/scoreimmobilier-desktop"
if [[ ! -x "$BIN_SRC" ]]; then
  BIN_SRC="$ROOT/../src-tauri/target/release/scoreimmobilier_desktop_tauri"
fi
ICON_SRC="$ROOT/icon.png"
if [[ ! -f "$ICON_SRC" ]]; then
  ICON_SRC="$ROOT/../src-tauri/icons/icon.png"
fi
DESKTOP_SRC="$ROOT/scoreimmobilier-desktop.desktop"

if [[ ! -x "$BIN_SRC" ]]; then
  echo "Binaire introuvable. Compilez d'abord : npm run build" >&2
  echo "Cherché : $ROOT/scoreimmobilier-desktop" >&2
  echo "          $ROOT/../src-tauri/target/release/scoreimmobilier_desktop_tauri" >&2
  exit 1
fi
if [[ ! -f "$ICON_SRC" ]]; then
  echo "Icône introuvable : $ICON_SRC" >&2
  exit 1
fi
if [[ ! -f "$DESKTOP_SRC" ]]; then
  echo "Lanceur introuvable : $DESKTOP_SRC" >&2
  exit 1
fi

missing=()
for lib in libwebkit2gtk-4.1.so.0 libgtk-3.so.0; do
  if ! ldconfig -p 2>/dev/null | grep -q "$lib"; then
    if ! find /lib /usr/lib /usr/lib64 -name "$lib" 2>/dev/null | grep -q .; then
      missing+=("$lib")
    fi
  fi
done
if ((${#missing[@]})); then
  echo "Dépendances manquantes : ${missing[*]}" >&2
  echo "Debian/Ubuntu : sudo apt install libwebkit2gtk-4.1-0 libgtk-3-0" >&2
  echo "Fedora        : sudo dnf install webkit2gtk4.1 gtk3" >&2
  echo "Arch          : sudo pacman -S webkit2gtk-4.1 gtk3" >&2
  echo "(L'AppImage embarque ces libs — utilisez-la si apt/dnf n'est pas possible.)" >&2
  exit 1
fi

mkdir -p "$BIN_DIR" "$APP_DIR" "$ICON_DIR"
install -m 755 "$BIN_SRC" "$BIN_DST"
install -m 644 "$ICON_SRC" "$ICON_DST"
sed "s|^Exec=.*|Exec=$BIN_DST|" "$DESKTOP_SRC" \
  | sed "s|^Icon=.*|Icon=$ICON_DST|" \
  > "$DESKTOP_DST"
chmod 644 "$DESKTOP_DST"

if command -v update-desktop-database >/dev/null 2>&1; then
  update-desktop-database "$APP_DIR" >/dev/null 2>&1 || true
fi
if command -v gtk-update-icon-cache >/dev/null 2>&1; then
  gtk-update-icon-cache -f "$PREFIX/share/icons/hicolor" >/dev/null 2>&1 || true
fi

echo "Installé : $BIN_DST"
echo "Lanceur  : $DESKTOP_DST"
echo "Données  : $HOME/.scoreimmobilier-desktop"
if [[ ":$PATH:" != *":$BIN_DIR:"* ]]; then
  echo "Ajoutez $BIN_DIR à PATH, ou lancez : $BIN_DST"
else
  echo "Lancer   : scoreimmobilier-desktop"
fi
