#!/usr/bin/env bash
# Bootstrap linuxdeploy + linuxdeploy-plugin-qt to a script-local cache.
#
# When SOURCED:   exposes $LINUXDEPLOY_BIN and $LINUXDEPLOY_PLUGIN_QT_BIN paths
#                 (downloads on first run if missing).
# When EXECUTED:  ensures both binaries are present and prints their paths.
#
# Pinned per spec §F9 — version bumps are deliberate, not transparent.
# To bump: re-run discovery (Task 5 Step 1 of the implementation plan), update
#          the two TAG variables below, and verify a fresh AppImage build.
#
# Spec: sethlabels-docs/specs/2026-04-29-packaging-design.md §F9
set -euo pipefail

# === PINNED VERSIONS (update deliberately per F9) ===
LINUXDEPLOY_TAG="1-alpha-20251107-1"
LINUXDEPLOY_PLUGIN_QT_TAG="1-alpha-20250213-1"
# ====================================================

CACHE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)/.cache"
LINUXDEPLOY_BIN="$CACHE_DIR/linuxdeploy-${LINUXDEPLOY_TAG}-x86_64.AppImage"
LINUXDEPLOY_PLUGIN_QT_BIN="$CACHE_DIR/linuxdeploy-plugin-qt-${LINUXDEPLOY_PLUGIN_QT_TAG}-x86_64.AppImage"

LINUXDEPLOY_URL="https://github.com/linuxdeploy/linuxdeploy/releases/download/${LINUXDEPLOY_TAG}/linuxdeploy-x86_64.AppImage"
LINUXDEPLOY_PLUGIN_QT_URL="https://github.com/linuxdeploy/linuxdeploy-plugin-qt/releases/download/${LINUXDEPLOY_PLUGIN_QT_TAG}/linuxdeploy-plugin-qt-x86_64.AppImage"

ensure_tool() {
  local url="$1" out="$2" label="$3"
  if [ -x "$out" ]; then
    return 0
  fi
  mkdir -p "$(dirname "$out")"
  echo "Downloading $label from $url ..." >&2
  if ! wget -q --show-progress -O "$out" "$url"; then
    echo "ERROR: download failed for $label ($url)" >&2
    rm -f "$out"
    return 1
  fi
  chmod +x "$out"
}

ensure_tool "$LINUXDEPLOY_URL" "$LINUXDEPLOY_BIN" "linuxdeploy"
ensure_tool "$LINUXDEPLOY_PLUGIN_QT_URL" "$LINUXDEPLOY_PLUGIN_QT_BIN" "linuxdeploy-plugin-qt"

export LINUXDEPLOY_BIN LINUXDEPLOY_PLUGIN_QT_BIN

if [ "${BASH_SOURCE[0]}" = "${0}" ]; then
  echo "linuxdeploy:           $LINUXDEPLOY_BIN"
  echo "linuxdeploy-plugin-qt: $LINUXDEPLOY_PLUGIN_QT_BIN"
fi
