#!/bin/sh
# Scry launcher — installed by the scry .deb at /opt/scry/scry-launcher.
#
# The .deb is a THIN delivery + desktop-integration shim: the artifact that
# actually RUNS (and self-updates in place, exactly as the raw-AppImage install
# always has) is a per-user copy of the GUI client AppImage. This script
# seeds/refreshes that copy from the root-owned seed the package ships, then
# execs it. It has nothing to do with the separate always-on Scry.Host
# service (see packaging/scry-install-service) — that install path is
# untouched by this launcher.
#
#   Seed (root-owned, replaced only by dpkg):   /opt/scry/Scry.AppImage
#   Live app (user-writable, self-updating):    ~/.local/share/scry/Scry.AppImage
#
# Because we exec the per-user AppImage file itself, the AppImage runtime sets
# $APPIMAGE to that user-writable path — so the in-app updater's
# apply-and-restart (AppImage self-replace) keeps working unchanged, and any
# .desktop/scheme registration the app writes points at a stable path instead
# of ~/Downloads.
#
# Seeding rules (never fight the in-app updater):
#   * no user copy yet                                  -> seed it
#   * .deb upgraded to a seed NEWER than the last seed  -> re-seed
#   * otherwise                                         -> leave the user copy
#     alone (the in-app updater may have moved it ahead of the seed; it wins)
set -eu

SEED_DIR="/opt/scry"
SEED="$SEED_DIR/Scry.AppImage"
SEED_VERSION="$(cat "$SEED_DIR/seed-version" 2>/dev/null || echo 0)"

DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}"
APP_DIR="$DATA_HOME/scry"
APP="$APP_DIR/Scry.AppImage"
MARKER="$APP_DIR/.seeded-version"

seed_app() {
    mkdir -p "$APP_DIR"
    # Copy to a temp name, then move into place: a crash mid-copy can never
    # leave a half-written AppImage at the exec path, and we never truncate a
    # file another process is currently running (mv swaps the inode).
    tmp="$APP_DIR/.Scry.AppImage.seed.$$"
    cp "$SEED" "$tmp"
    chmod 755 "$tmp"
    mv -f "$tmp" "$APP"
    printf '%s\n' "$SEED_VERSION" > "$MARKER"
}

if [ ! -x "$APP" ]; then
    seed_app
else
    LAST_SEEDED="$(cat "$MARKER" 2>/dev/null || echo 0)"
    # dpkg --compare-versions exits non-zero for "not greater" AND for parse
    # errors; both conflate to "do not re-seed", which is the safe default
    # (never clobber a copy the in-app updater may have advanced).
    if dpkg --compare-versions "$SEED_VERSION" gt "$LAST_SEEDED" 2>/dev/null; then
        seed_app
    fi
fi

exec "$APP" "$@"
