#!/usr/bin/env bash
# Install WriTea for the current user so it shows up in the applications menu with
# its proper icon (Linux takes the launcher/taskbar icon from an installed
# .desktop + icon-theme file, NOT from the binary itself).
#
# Run this from the directory that holds `writea` and `writea.png`
# (the files produced by the Docker build into ./dist), e.g.:
#
#   ./install-linux.sh
#
# Uninstall: ./install-linux.sh --uninstall
set -euo pipefail

APP=writea
NAME=WriTea
BIN_DIR="${XDG_BIN_HOME:-$HOME/.local/bin}"
DATA_DIR="${XDG_DATA_HOME:-$HOME/.local/share}"
DESKTOP_DIR="$DATA_DIR/applications"
ICON_DIR="$DATA_DIR/icons/hicolor/256x256/apps"

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

if [[ "${1:-}" == "--uninstall" ]]; then
    rm -f "$BIN_DIR/$APP" "$DESKTOP_DIR/$APP.desktop" "$ICON_DIR/$APP.png"
    echo "Removed $NAME (binary, launcher, icon)."
    update-desktop-database "$DESKTOP_DIR" 2>/dev/null || true
    gtk-update-icon-cache -f -t "$DATA_DIR/icons/hicolor" 2>/dev/null || true
    exit 0
fi

[[ -f "$here/$APP" ]]      || { echo "error: '$APP' binary not found next to this script." >&2; exit 1; }
[[ -f "$here/$APP.png" ]]  || { echo "error: '$APP.png' icon not found next to this script." >&2; exit 1; }

mkdir -p "$BIN_DIR" "$DESKTOP_DIR" "$ICON_DIR"

install -m 0755 "$here/$APP" "$BIN_DIR/$APP"
install -m 0644 "$here/$APP.png" "$ICON_DIR/$APP.png"

# Write the .desktop with an absolute Exec so it works whether or not ~/.local/bin
# is on PATH; keep StartupWMClass matching the app's window app_id.
cat > "$DESKTOP_DIR/$APP.desktop" <<EOF
[Desktop Entry]
Type=Application
Version=1.0
Name=$NAME
GenericName=Document Editor
Comment=A page-oriented text & vector document editor
Exec=$BIN_DIR/$APP %f
Icon=$APP
Terminal=false
Categories=Office;WordProcessor;Graphics;VectorGraphics;
StartupWMClass=$APP
StartupNotify=true
EOF
chmod 0644 "$DESKTOP_DIR/$APP.desktop"

# Refresh the desktop/icon caches (harmless if the tools are absent).
update-desktop-database "$DESKTOP_DIR" 2>/dev/null || true
gtk-update-icon-cache -f -t "$DATA_DIR/icons/hicolor" 2>/dev/null || true

echo "Installed $NAME:"
echo "  binary   $BIN_DIR/$APP"
echo "  icon     $ICON_DIR/$APP.png"
echo "  launcher $DESKTOP_DIR/$APP.desktop"
echo
case ":$PATH:" in
    *":$BIN_DIR:"*) : ;;
    *) echo "note: $BIN_DIR is not on your PATH — launch from the applications menu, or add it." ;;
esac
echo "You should now find “$NAME” in your applications menu, with its icon."
