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

usage() {
  printf 'usage: %s [--user] [--prefix /usr/local] [--exec /path/to/anothereditor]\n' "$0" >&2
}

MODE="system"
PREFIX="${PREFIX:-/usr/local}"
EXEC_PATH="${ANOTHEREDITOR_EXEC:-anothereditor}"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --user)
      MODE="user"
      shift
      ;;
    --prefix)
      PREFIX="${2:-}"
      [[ -n "${PREFIX}" ]] || { usage; exit 2; }
      shift 2
      ;;
    --exec)
      EXEC_PATH="${2:-}"
      [[ -n "${EXEC_PATH}" ]] || { usage; exit 2; }
      shift 2
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      usage
      exit 2
      ;;
  esac
done

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
if [[ "${MODE}" == "user" ]]; then
  DATA_HOME="${XDG_DATA_HOME:-${HOME}/.local/share}"
else
  DATA_HOME="${PREFIX}/share"
fi

desktop_dir="${DATA_HOME}/applications"
mime_dir="${DATA_HOME}/mime/packages"
icon_dir="${DATA_HOME}/icons/hicolor/scalable/apps"

mkdir -p "${desktop_dir}" "${mime_dir}" "${icon_dir}"

desktop_tmp="$(mktemp)"
sed "s|^Exec=.*|Exec=${EXEC_PATH} %F|" \
  "${ROOT}/packaging/linux/anothereditor.desktop" > "${desktop_tmp}"
install -m 0644 "${desktop_tmp}" "${desktop_dir}/anothereditor.desktop"
rm -f "${desktop_tmp}"

install -m 0644 "${ROOT}/packaging/linux/anothereditor-mime.xml" "${mime_dir}/anothereditor.xml"
install -m 0644 "${ROOT}/packaging/linux/anothereditor.svg" "${icon_dir}/anothereditor.svg"

if command -v update-mime-database >/dev/null 2>&1; then
  update-mime-database "${DATA_HOME}/mime" >/dev/null 2>&1 || true
fi

if command -v update-desktop-database >/dev/null 2>&1; then
  update-desktop-database "${desktop_dir}" >/dev/null 2>&1 || true
fi

if command -v gtk-update-icon-cache >/dev/null 2>&1; then
  gtk-update-icon-cache -q -t "${DATA_HOME}/icons/hicolor" >/dev/null 2>&1 || true
fi

echo "Installed AnotherEditor Linux desktop integration under ${DATA_HOME}."
