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

APP_NAME="Raphael"
ICON_NAME="raphael"
CATEGORIES="AudioVideo;"
COMMENT="Slideshow Video Creator"

INSTALL_DIR="${HOME}/Applications"
DESKTOP_DIR="${HOME}/.local/share/applications"
ICON_THEME_DIR="${HOME}/.local/share/icons/hicolor/256x256/apps"
PIXMAP_DIR="${HOME}/.local/share/pixmaps"

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

APPIMAGE_SRC="$(ls -1 "${SCRIPT_DIR}"/Raphael-*.AppImage 2>/dev/null | head -n 1 || true)"

if [[ -z "${APPIMAGE_SRC}" ]]; then
  echo "ERROR: No Raphael AppImage found next to install.sh"
  exit 1
fi

mkdir -p "${INSTALL_DIR}" "${DESKTOP_DIR}" "${ICON_THEME_DIR}" "${PIXMAP_DIR}"

APPIMAGE_BASENAME="$(basename "${APPIMAGE_SRC}")"
APPIMAGE_DST="${INSTALL_DIR}/${APPIMAGE_BASENAME}"

echo "==> Removing older Raphael AppImages"
rm -f "${INSTALL_DIR}/Raphael-"*.AppImage 2>/dev/null || true

echo "==> Installing AppImage to: ${APPIMAGE_DST}"
cp -f "${APPIMAGE_SRC}" "${APPIMAGE_DST}"
chmod +x "${APPIMAGE_DST}"

echo "==> Installing icon"
BUNDLED_ICON="${SCRIPT_DIR}/${ICON_NAME}.png"

if [[ -f "${BUNDLED_ICON}" ]]; then
  cp -f "${BUNDLED_ICON}" "${ICON_THEME_DIR}/${ICON_NAME}.png"
  cp -f "${BUNDLED_ICON}" "${PIXMAP_DIR}/${ICON_NAME}.png"
else
  echo "WARN: raphael.png not found next to install.sh"
fi

chmod 644 "${ICON_THEME_DIR}/${ICON_NAME}.png" 2>/dev/null || true
chmod 644 "${PIXMAP_DIR}/${ICON_NAME}.png" 2>/dev/null || true

DESKTOP_FILE="${DESKTOP_DIR}/${ICON_NAME}.desktop"
ICON_ABS="${PIXMAP_DIR}/${ICON_NAME}.png"

echo "==> Writing desktop launcher: ${DESKTOP_FILE}"
cat > "${DESKTOP_FILE}" <<EOF
[Desktop Entry]
Type=Application
Name=${APP_NAME}
Comment=${COMMENT}
Exec=${APPIMAGE_DST} %U
Icon=${ICON_ABS}
Terminal=false
Categories=${CATEGORIES}
StartupWMClass=Raphael
EOF

chmod 644 "${DESKTOP_FILE}"

echo "==> Refreshing desktop caches"
command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "${DESKTOP_DIR}" || true
command -v xdg-desktop-menu >/dev/null 2>&1 && xdg-desktop-menu forceupdate || true
command -v kbuildsycoca5 >/dev/null 2>&1 && kbuildsycoca5 --noincremental || true
command -v kbuildsycoca6 >/dev/null 2>&1 && kbuildsycoca6 --noincremental || true

echo
echo "Installed!"
echo "• Launch from your application menu by searching: ${APP_NAME}"
