#!/bin/sh
# PhotoCraft AppImage entry point (packaging/linux/AppRun; installed by package.sh).
#
# On Wayland the compositor resolves a window's dock icon by taking the window's
# app_id (ai.storyteller.photocraft) and looking up an installed .desktop file.
# An AppImage installs nothing, so every AppImage run would otherwise show the
# generic "Wayland" icon (#593). Best-effort desktop integration: on first run
# (and whenever the AppImage's path changes) install the .desktop entry and the
# hicolor icons into $XDG_DATA_HOME, then launch. Every failure here must leave
# the launch untouched. Opt out with PHOTOCRAFT_NO_DESKTOP_INTEGRATION=1.

set -u

APPDIR="$(dirname "$(readlink -f "$0")")"
DESK_ID=ai.storyteller.photocraft

# Select the bundled headless binary before desktop integration. In particular,
# an MCP launch must leave stdio untouched and must not install a GUI launcher.
if [ "${1:-}" = --cli ]; then
  shift
  exec "$APPDIR/usr/bin/photocraft-cli" "$@"
fi
# Type 2 runtimes preserve a symlink's original name in ARGV0.
case "${ARGV0:-}" in
  photocraft-cli | */photocraft-cli) exec "$APPDIR/usr/bin/photocraft-cli" "$@" ;;
esac

# A damaged snapshot is not evidence that an absent user key was newly added.
# Treat it like a legacy installation and preserve the existing launcher.
valid_baseline() {
  [ -f "$1" ] && [ ! -L "$1" ] && [ -s "$1" ] || return 1
  awk '
    /^\[/ { group = $0; if (group == "[Desktop Entry]") sections++; next }
    /^[ \t]*($|#)/ { next }
    /^[^= \t][^=]*=/ {
      name = $0; sub(/=.*/, "", name)
      k = group SUBSEP name
      if (seen[k]++) bad = 1
      if (group == "[Desktop Entry]") {
        if ($0 == "Type=Application") type = 1
        if ($0 ~ /^Name=.+$/) title = 1
        if ($0 ~ /^Exec=".+" %F$/) executable = 1
      }
      next
    }
    { bad = 1 }
    END { exit !(sections == 1 && type && title && executable && !bad) }
  ' "$1"
}

integrate() {
  case "${PHOTOCRAFT_NO_DESKTOP_INTEGRATION:-}" in
    1 | true | yes) return 0 ;;
  esac
  # The AppImage runtime exports $APPIMAGE; without it (an extracted AppDir) there
  # is no path to register and nothing to do.
  appimage="${APPIMAGE:-}"
  [ -n "$appimage" ] && [ -f "$appimage" ] || return 0
  appimage="$(readlink -f "$appimage")" || return 0
  # Exec= is parsed by the desktop: a path holding a quote, backquote, dollar, backslash,
  # percent or a line break would need escaping (or could add lines), so skip integration.
  case "$appimage" in
    *[\"\`\$\\%]* | *'
'*) return 0 ;;
  esac
  home="${HOME:-}"
  [ -n "$home" ] || return 0
  data="${XDG_DATA_HOME:-$home/.local/share}"
  src_desktop="$APPDIR/usr/share/applications/$DESK_ID.desktop"
  [ -f "$src_desktop" ] || return 0

  # If another integrator already registered a .desktop whose Exec points at this
  # AppImage, do not write a second launcher (#3623); remove our own if one is left
  # over, and still install the hicolor icons below. $DESKTOPINTEGRATION is not that
  # signal: PhotoCraft sets X-AppImage-Integrate=false, so AppImageLauncher skips the
  # AppImage and still exports the variable on its binfmt bypass. Treating it as
  # "already integrated" left the menu with no entry (#5534).
  apps="$data/applications"
  mkdir -p "$apps" 2>/dev/null || return 0
  desktop="$apps/$DESK_ID.desktop"
  baseline="$apps/.$DESK_ID.generated"
  external=0
  for f in "$apps"/*.desktop; do
    if [ ! -f "$f" ] || [ "$f" = "$apps/$DESK_ID.desktop" ]; then
      continue
    fi
    if grep '^Exec=' "$f" 2>/dev/null | grep -Fq "$appimage"; then
      external=1
      break
    fi
  done
  # AM / AppMan (#6392) install their own launcher, whose Exec runs a command on
  # PATH rather than this AppImage, so the check above misses it. AM's author
  # names the only two places it writes one: system-wide for AM, per user for
  # AppMan and rootless installs.
  for f in /usr/local/share/applications/photocraft-AM.desktop "$apps/photocraft-AM.desktop"; do
    if [ -f "$f" ]; then
      external=1
      break
    fi
  done
  if [ -L "$desktop" ] || [ -L "$baseline" ] ||
    { [ -e "$desktop" ] && [ ! -f "$desktop" ]; } ||
    { [ -e "$baseline" ] && [ ! -f "$baseline" ]; }; then
    # A link (including a dangling one) or special file is not our installation.
    # Leave both launcher and snapshot alone; icons may still be installed below.
    :
  elif [ "$external" = 1 ]; then
    # Only a byte-identical, valid generated snapshot proves this is ours to
    # remove. A customized or legacy launcher belongs to the user.
    if [ -f "$desktop" ] && valid_baseline "$baseline" && cmp -s "$baseline" "$desktop" && [ ! -L "$desktop" ]; then
      if rm -f "$desktop" 2>/dev/null; then
        command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$apps" >/dev/null 2>&1
      fi
    fi
  else
    # Rewrite Exec to this AppImage (the binary is not on the host PATH) and drop
    # TryExec, which would hide the entry; everything else is shipped as packaged.
    tmp="$apps/.$DESK_ID.tmp.$$"
    esc="$(printf '%s' "$appimage" | sed 's/[\\&|]/\\&/g')"
    if sed -e "s|^Exec=.*|Exec=\"$esc\" %F|" -e '/^TryExec=/d' "$src_desktop" 2>/dev/null >"$tmp"; then
      generated="$tmp.generated"
      cp "$tmp" "$generated" 2>/dev/null || { rm -f "$tmp"; return 0; }
      if [ -f "$desktop" ]; then
        # Three-way merge: update shipped keys only if the user has not changed
        # them. Keep custom keys, comments and deletions. The snapshot is hidden
        # and has no .desktop suffix, so desktop menus do not discover it.
        # For older installs without a snapshot, the current template is the
        # conservative baseline. An unknown previous executable is left alone.
        previous="$baseline"
        bootstrap=0
        if ! valid_baseline "$previous"; then
          previous="$tmp.previous"
          cp "$generated" "$previous" 2>/dev/null || { rm -f "$tmp" "$generated"; return 0; }
          bootstrap=1
        fi
        if ! awk -v bootstrap="$bootstrap" '
          function key(line) {
            if (line ~ /^\[/) { group = line; return "" }
            if (line ~ /^[^#= \t][^=]*=/) {
              name = line; sub(/=.*/, "", name); return group SUBSEP name
            }
            return ""
          }
          FNR == 1 { group = "" }
          FILENAME == ARGV[1] {
            k = key($0); if (k != "") old[k] = $0
            if (group == "[Desktop Entry]" && $0 ~ /^Exec=".*" %F$/)
              old_exec = substr($0, 6, length($0) - 8)
            next
          }
          FILENAME == ARGV[2] {
            k = key($0); if (k != "") { fresh[k] = $0; order[++n] = k }
            if (group == "[Desktop Entry]" && $0 ~ /^Exec=/)
              new_exec = substr($0, 6, length($0) - 8)
            next
          }
          function additions( i, k) {
            for (i = 1; i <= n; i++) {
              k = order[i]
              if (index(k, "[Desktop Entry]" SUBSEP) == 1 && !(k in old) && !(k in seen))
                print fresh[k]
            }
          }
          {
            if ($0 ~ /^\[/ && group == "[Desktop Entry]") additions()
            k = key($0)
            if (k != "") {
              seen[k] = 1
              if (k in old && $0 == old[k]) {
                if (k in fresh) print fresh[k]
                next
              }
              if (group == "[Desktop Entry]" && name == "Exec") {
                # Literal substitution, never a regex or shell evaluation: keep
                # environment wrappers and arguments around the managed path.
                pos = index($0, old_exec)
                prefix = substr($0, 1, pos - 1)
                if (old_exec != "" && pos > 0 && prefix ~ /^Exec=(env[ \t]+([^ \t=]+=[^ \t]*[ \t]+)*)?$/)
                  $0 = substr($0, 1, pos - 1) new_exec substr($0, pos + length(old_exec))
              }
            }
            print
          }
          END { if (group == "[Desktop Entry]") additions() }
        ' "$previous" "$generated" "$desktop" >"$tmp"; then
          rm -f "$tmp" "$generated"
          [ "$bootstrap" = 0 ] || rm -f "$previous"
          return 0
        fi
        [ "$bootstrap" = 0 ] || rm -f "$previous"
      fi
      if cmp -s "$tmp" "$desktop"; then
        rm -f "$tmp"
      else
        if mv -f "$tmp" "$desktop" 2>/dev/null; then
          command -v update-desktop-database >/dev/null 2>&1 && update-desktop-database "$apps" >/dev/null 2>&1
        else
          rm -f "$tmp" "$generated"
          return 0
        fi
      fi
      mv -f "$generated" "$baseline" 2>/dev/null || rm -f "$generated"
    else
      rm -f "$tmp"
      return 0
    fi

  fi

  # Icons: per-file compare so an unchanged install costs a handful of cmp calls.
  src_icons="$APPDIR/usr/share/icons/hicolor"
  [ -d "$src_icons" ] || return 0
  icons="$data/icons/hicolor"
  (cd "$src_icons" && find . -type f) | while IFS= read -r rel; do
    mkdir -p "$icons/$(dirname "$rel")" 2>/dev/null || continue
    if ! cmp -s "$src_icons/$rel" "$icons/$rel"; then
      cp "$src_icons/$rel" "$icons/$rel" 2>/dev/null || true
    fi
  done
}

# `PhotoCraft.AppImage --cli <args>` runs the bundled photocraft-cli: MCP clients start
# `--cli mcp` this way (the ArtCraft Launcher's app list), since the mount point that holds
# the CLI changes with every run.
if [ "${1:-}" = "--cli" ]; then
  shift
  exec "$APPDIR/usr/bin/photocraft-cli" "$@"
fi

integrate
exec "$APPDIR/usr/bin/photocraft" "$@"
