#!/usr/bin/env bash
# Register this portable FunGen bundle with the desktop, per-user.
#
# The Linux build ships as a self-contained tarball (no system package),
# so file associations aren't wired up on extract. Run this once from
# inside the extracted FunGen/ folder to:
#   - install a .desktop entry pointing Exec= at THIS folder's binary
#   - declare the .funscript / .fungen MIME types (shared-mime-info)
#   - install the hicolor icon set
#   - make FunGen the default handler for both extensions
#
# Everything lands under ~/.local/share (no root, no admin). Re-runnable.
# Undo with ./uninstall.sh.
#
# Usage:  ./install.sh
set -euo pipefail

HERE="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
BIN="$HERE/fungen"
if [[ ! -x "$BIN" ]]; then
    echo "error: $BIN not found - run this from inside the extracted FunGen/ folder." >&2
    exit 1
fi

DATA="${XDG_DATA_HOME:-$HOME/.local/share}"
APPS="$DATA/applications"
MIMEPKG="$DATA/mime/packages"
ICONS="$DATA/icons/hicolor"
mkdir -p "$APPS" "$MIMEPKG" "$ICONS"

# Desktop entry: copy the shipped one but point Exec/Icon at this folder
# (absolute paths) so the launcher works regardless of $PATH. %F passes
# the double-clicked file(s) as arguments, which fungen routes by
# extension at startup.
echo "==> installing desktop entry"
DESKTOP="$APPS/fungen.desktop"
sed -E \
    -e "s|^Exec=.*|Exec=\"$BIN\" %F|" \
    -e "s|^Icon=.*|Icon=fungen|" \
    "$HERE/share/applications/fungen.desktop" > "$DESKTOP"
chmod +x "$DESKTOP"

# MIME type definitions for .funscript / .fungen (globs + JSON sub-class).
echo "==> installing MIME types"
cp "$HERE/share/mime/packages/fungen-mime.xml" "$MIMEPKG/fungen-mime.xml"

# Icons: copy the shipped hicolor tree into the user icon theme.
if [[ -d "$HERE/share/icons/hicolor" ]]; then
    echo "==> installing icons"
    cp -r "$HERE/share/icons/hicolor/." "$ICONS/"
fi

# Refresh the databases so the new entry/types are visible immediately.
command -v update-mime-database     >/dev/null && update-mime-database "$DATA/mime" || true
command -v update-desktop-database  >/dev/null && update-desktop-database "$APPS"   || true
command -v gtk-update-icon-cache    >/dev/null && gtk-update-icon-cache -q -t -f "$ICONS" 2>/dev/null || true

# Make FunGen the default handler for both document types. xdg-mime is
# part of xdg-utils (present on every desktop distro); if it's missing
# the entry is still registered and the user can pick it via "Open with".
if command -v xdg-mime >/dev/null; then
    echo "==> setting FunGen as default for .funscript and .fungen"
    xdg-mime default fungen.desktop application/x-funscript      || true
    xdg-mime default fungen.desktop application/x-fungen-project || true
else
    echo "    (xdg-mime not found - registered, but set the default via your file manager's \"Open with\")"
fi

echo
echo "==> done. FunGen now opens .funscript and .fungen files."
echo "    If your file manager still shows the old handler, log out/in once."
