#!/usr/bin/env bash
#
# cftool-desktop-setup.sh - register the CFTool AppImage with your Linux desktop.
#
# After running this once, CFTool appears in your applications menu and .cfp
# project files open in CFTool when you double-click them.
#
#   ./cftool-desktop-setup.sh [/path/to/CFTool-x86_64.AppImage]
#   ./cftool-desktop-setup.sh --uninstall
#
# If you don't pass a path, it looks for a single CFTool-*.AppImage next to this
# script. Everything is installed per-user under ~/.local (no sudo needed).
#
# NOTE: the association points at the AppImage where it currently lives. If you
# MOVE the AppImage later, just run this script again.
#
set -euo pipefail

APP_ID="cftool"
APP_NAME="CFTool"
MIME="application/x-cftool-project"
GLOB="*.cfp"

DATA="${XDG_DATA_HOME:-$HOME/.local/share}"
APPS_DIR="$DATA/applications"
MIME_DIR="$DATA/mime"
ICON_DIR="$DATA/icons/hicolor/256x256/apps"
DESKTOP="$APPS_DIR/$APP_ID.desktop"
MIME_XML="$MIME_DIR/packages/$APP_ID.xml"
ICON_PNG="$ICON_DIR/$APP_ID.png"

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

refresh_caches() {
  update-mime-database "$MIME_DIR" >/dev/null 2>&1 || true
  update-desktop-database "$APPS_DIR" >/dev/null 2>&1 || true
  # KDE keeps its own cache; harmless (and silent) on other desktops.
  kbuildsycoca6 >/dev/null 2>&1 || kbuildsycoca5 >/dev/null 2>&1 || true
  gtk-update-icon-cache -f -t "$DATA/icons/hicolor" >/dev/null 2>&1 || true
}

uninstall() {
  echo ">>> Removing CFTool desktop integration..."
  rm -f "$DESKTOP" "$MIME_XML" "$ICON_PNG"
  refresh_caches
  echo ">>> Done. CFTool and the .cfp association have been removed."
  echo "    (The AppImage file itself was left untouched.)"
}

if [[ "${1:-}" == "--uninstall" || "${1:-}" == "-u" ]]; then
  uninstall
  exit 0
fi

# --- locate the AppImage -----------------------------------------------------
APPIMAGE="${1:-}"
if [[ -z "$APPIMAGE" ]]; then
  shopt -s nullglob
  candidates=("$SCRIPT_DIR"/CFTool-*.AppImage "$SCRIPT_DIR"/cftool-*.AppImage)
  shopt -u nullglob
  if [[ ${#candidates[@]} -eq 1 ]]; then
    APPIMAGE="${candidates[0]}"
  else
    echo "Usage: $0 /path/to/CFTool-x86_64.AppImage"
    echo "       $0 --uninstall"
    if [[ ${#candidates[@]} -gt 1 ]]; then
      echo "!!! Found more than one CFTool AppImage next to this script; name one explicitly."
    else
      echo "!!! No CFTool-*.AppImage found next to this script; pass its path."
    fi
    exit 1
  fi
fi

APPIMAGE="$(readlink -f "$APPIMAGE")"
[[ -f "$APPIMAGE" ]] || { echo "!!! AppImage not found: $APPIMAGE"; exit 1; }
chmod +x "$APPIMAGE" 2>/dev/null || true

echo ">>> Installing CFTool desktop integration for: $APPIMAGE"
mkdir -p "$APPS_DIR" "$MIME_DIR/packages" "$ICON_DIR"

# --- MIME type for .cfp ------------------------------------------------------
cat > "$MIME_XML" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
  <mime-type type="$MIME">
    <comment>CFTool project</comment>
    <glob pattern="$GLOB"/>
    <icon name="$APP_ID"/>
  </mime-type>
</mime-info>
EOF

# --- icon (optional): prefer a local cftool.png, else pull it from the AppImage
install_icon() {
  if [[ -f "$SCRIPT_DIR/$APP_ID.png" ]]; then
    cp "$SCRIPT_DIR/$APP_ID.png" "$ICON_PNG"
    return 0
  fi
  # --appimage-extract unpacks the squashfs directly; no FUSE/libfuse2 needed.
  local tmp; tmp="$(mktemp -d)"
  ( cd "$tmp" && "$APPIMAGE" --appimage-extract "$APP_ID.png" >/dev/null 2>&1 ) || true
  if [[ -f "$tmp/squashfs-root/$APP_ID.png" ]]; then
    cp "$tmp/squashfs-root/$APP_ID.png" "$ICON_PNG"
  fi
  rm -rf "$tmp"
}
install_icon || true

# --- desktop entry (Exec is quoted so a path with spaces still works) --------
cat > "$DESKTOP" <<EOF
[Desktop Entry]
Type=Application
Name=$APP_NAME
Comment=Curve fitting tool
Exec="$APPIMAGE" %f
Icon=$APP_ID
Categories=Science;Education;
Terminal=false
MimeType=$MIME;
EOF
chmod +x "$DESKTOP" 2>/dev/null || true

# --- make CFTool the default handler for .cfp, then refresh caches -----------
xdg-mime default "$APP_ID.desktop" "$MIME" >/dev/null 2>&1 || true
refresh_caches

echo ">>> Done."
echo "    - CFTool is now in your applications menu."
echo "      (On GNOME you may need to log out and back in for it to appear;"
echo "       KDE/XFCE usually show it right away.)"
echo "    - .cfp files will open in CFTool (double-click one to test)."
echo "    - If you move the AppImage, re-run this script."
echo "    - To undo: $0 --uninstall"
