#!/usr/bin/env bash
# RakuOS Software launcher — auto-detects installed GTK or Qt frontend.

LIBEXEC=/usr/libexec/rakuos/software

CACHE_DIR="$HOME/.cache/rakuos"
WARMUP_FLAG="$CACHE_DIR/software-warmed"

mkdir -p "$CACHE_DIR"

# --- warmup only if not already done ---
if [ ! -f "$WARMUP_FLAG" ]; then
    touch "$WARMUP_FLAG"

    # warmup run (fire and forget)
    if [ -x "$LIBEXEC/rakuos-software-gtk" ]; then
        "$LIBEXEC/rakuos-software-gtk" "$@" &
    elif [ -x "$LIBEXEC/rakuos-software-qt" ]; then
        "$LIBEXEC/rakuos-software-qt" "$@" &
    else
        echo "rakuos-software: no frontend installed (expected gtk or qt in $LIBEXEC)" >&2
        exit 1
    fi
    WARMUP_PID=$!

    # give it just enough time to initialize
    sleep 3

    # kill warmup backend + tray immediately
    kill "$WARMUP_PID" 2>/dev/null
    pkill -x rakuos-software-tray 2>/dev/null
    sleep 3
fi

# --- normal run (always exactly once) ---
if [ -x "$LIBEXEC/rakuos-software-gtk" ]; then
    exec "$LIBEXEC/rakuos-software-gtk" "$@"
elif [ -x "$LIBEXEC/rakuos-software-qt" ]; then
    exec "$LIBEXEC/rakuos-software-qt" "$@"
else
    echo "rakuos-software: no frontend installed (expected gtk or qt in $LIBEXEC)" >&2
    exit 1
fi
