#!/usr/bin/env bash
set -euo pipefail

# Build an AppImage when the host mounts /tmp with noexec.
# Usage: build-appimage-noexec.sh <AppDir> <output.AppImage> <tauri-cache-dir> [runtime-x86_64]

APP_DIR="${1:-}"
OUTPUT_FILE="${2:-}"
TAURI_CACHE_DIR="${3:-}"
RUNTIME_FILE="${4:-}"

if [[ -z "$APP_DIR" || -z "$OUTPUT_FILE" || -z "$TAURI_CACHE_DIR" ]]; then
  echo "Usage: $0 <AppDir> <output.AppImage> <tauri-cache-dir>"
  exit 1
fi
if [[ ! -d "$APP_DIR" ]]; then
  echo "AppDir not found: $APP_DIR"
  exit 1
fi

LINUXDEPLOY_IMAGE="$TAURI_CACHE_DIR/linuxdeploy-x86_64.AppImage"
APPIMAGE_PLUGIN="$TAURI_CACHE_DIR/linuxdeploy-plugin-appimage.AppImage"
GTK_PLUGIN="$TAURI_CACHE_DIR/linuxdeploy-plugin-gtk.sh"
for required in "$LINUXDEPLOY_IMAGE" "$APPIMAGE_PLUGIN" "$GTK_PLUGIN"; do
  if [[ ! -f "$required" ]]; then
    echo "Required Tauri AppImage tool not found: $required"
    exit 1
  fi
done

REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
CLI_VERSION="$(sed -n 's/^const BUNDLED_CLI_VERSION: &str = "\([^"]*\)";$/\1/p' "$REPO_ROOT/src-tauri/src/vigthoria_cli.rs")"
CLI_RESOURCE_NAME="vigthoria-cli-${CLI_VERSION}.tgz"
CLI_RESOURCE_SOURCE="$REPO_ROOT/resources/$CLI_RESOURCE_NAME"
if [[ -z "$CLI_VERSION" || ! -f "$CLI_RESOURCE_SOURCE" ]]; then
  echo "Bundled CLI resource is not configured correctly: $CLI_RESOURCE_SOURCE"
  exit 1
fi

# Tauri's target/_up_/resources directory persists across builds. The
# generated AppDir can therefore inherit obsolete CLI archives even though
# tauri.conf.json names only the current one. Remove only versioned CLI
# archives from the generated AppDir, then restore and verify the exact
# configured resource before linuxdeploy packages it.
while IFS= read -r resource_dir; do
  find "$resource_dir" -maxdepth 1 -type f -name 'vigthoria-cli-*.tgz' -delete
  install -m 0644 "$CLI_RESOURCE_SOURCE" "$resource_dir/$CLI_RESOURCE_NAME"
done < <(find "$APP_DIR" -type d -path '*/_up_/resources')

RESOURCE_COUNT="$(find "$APP_DIR" -type f -path '*/_up_/resources/vigthoria-cli-*.tgz' | wc -l)"
if [[ "$RESOURCE_COUNT" -ne 1 ]]; then
  echo "Expected exactly one bundled CLI archive in AppDir; found $RESOURCE_COUNT"
  exit 1
fi
if ! cmp -s "$CLI_RESOURCE_SOURCE" "$(find "$APP_DIR" -type f -path "*/_up_/resources/$CLI_RESOURCE_NAME" -print -quit)"; then
  echo "AppDir bundled CLI archive does not match $CLI_RESOURCE_SOURCE"
  exit 1
fi

TOOLS_ROOT="$REPO_ROOT/src-tauri/target/release/appimage-tools"
LINUXDEPLOY_ROOT="$TOOLS_ROOT/linuxdeploy"
APPIMAGETOOL_ROOT="$TOOLS_ROOT/appimagetool"

mkdir -p "$LINUXDEPLOY_ROOT" "$APPIMAGETOOL_ROOT" "$(dirname "$OUTPUT_FILE")"
(
  cd "$LINUXDEPLOY_ROOT"
  "$LINUXDEPLOY_IMAGE" --appimage-extract >/dev/null
)
(
  cd "$APPIMAGETOOL_ROOT"
  "$APPIMAGE_PLUGIN" --appimage-extract >/dev/null
)
install -m 0755 "$GTK_PLUGIN" "$LINUXDEPLOY_ROOT/squashfs-root/usr/bin/linuxdeploy-plugin-gtk.sh"

"$LINUXDEPLOY_ROOT/squashfs-root/AppRun" \
  --appdir "$APP_DIR" \
  --plugin gtk

APPIMAGETOOL="$APPIMAGETOOL_ROOT/squashfs-root/usr/bin/appimagetool"
APPIMAGETOOL_ARGS=(--no-appstream)
if [[ -n "$RUNTIME_FILE" ]]; then
  if [[ ! -f "$RUNTIME_FILE" ]]; then
    echo "AppImage runtime file not found: $RUNTIME_FILE"
    exit 1
  fi
  APPIMAGETOOL_ARGS+=(--runtime-file "$RUNTIME_FILE")
fi

ARCH=x86_64 "$APPIMAGETOOL" \
  "${APPIMAGETOOL_ARGS[@]}" \
  "$APP_DIR" \
  "$OUTPUT_FILE"
chmod 0755 "$OUTPUT_FILE"
echo "Built AppImage: $OUTPUT_FILE"
