#!/bin/sh
# Sticki.ly launcher — installed by the stickily .deb at /opt/stickily/stickily-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 AppImage. This script seeds/refreshes
# that copy from the root-owned seed the package ships, then execs it.
#
#   Seed (root-owned, replaced only by dpkg):   /opt/stickily/Stickily.AppImage
#   Live app (user-writable, self-updating):    ~/.local/share/stickily/Stickily.AppImage
#
# Because we exec the per-user AppImage file itself, the AppImage runtime sets
# $APPIMAGE to that user-writable path. Two things key off that:
#   * LaunchAtLogin (the tray app's autostart toggle) reads $APPIMAGE and writes
#     the user's own ~/.config/autostart entry pointed at THIS stable path
#     instead of a squashfs-fuse mount point that evaporates on reboot.
#   * The in-app updater (LinuxUpdateProvider — a GPG-verified tarball swap, NOT
#     Velopack) resolves the running binary via Environment.ProcessPath and
#     writes a new copy on top of it; running from a user-writable path (not the
#     root-owned /opt seed) keeps that swap able to write, unchanged from how a
#     raw AppImage downloaded straight into ~/Downloads has always behaved.
#
# 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/stickily"
SEED="$SEED_DIR/Stickily.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/stickily"
APP="$APP_DIR/Stickily.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/.Stickily.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" "$@"
