#!/usr/bin/env bash
# Wraps the jpackage app image (":composeApp:createReleaseDistributable") into a
# standalone AppImage. The app image already carries its own jlink runtime, so the
# AppDir only needs the AppImage entry points: AppRun, a .desktop file and an icon.
set -euo pipefail

if [[ $# != 1 ]]; then
  echo "Usage: bash scripts/build-linux-appimage.sh out.AppImage" >&2
  exit 2
fi

out=$1
repo_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
app_image="$repo_root/composeApp/build/compose/binaries/main-release/app/Yokan"
icon="$repo_root/composeApp/src/androidMain/res/mipmap-anydpi/ic_launcher.png"

[[ -x "$app_image/bin/Yokan" ]] || {
  echo "Run ./gradlew :composeApp:createReleaseDistributable first; missing $app_image/bin/Yokan" >&2
  exit 1
}
[[ -f "$icon" ]] || { echo "Icon does not exist: $icon" >&2; exit 1; }

arch=$(uname -m)
case "$arch" in
  x86_64 | aarch64) ;;
  *) echo "Unsupported AppImage architecture: $arch" >&2; exit 1 ;;
esac

work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
appdir="$work/Yokan.AppDir"

mkdir -p "$appdir/usr"
cp -a "$app_image/." "$appdir/usr/"
cp "$icon" "$appdir/yokan.png"

# appimagetool requires exactly one .desktop entry in the AppDir root, and its Icon
# key must name an image file sitting next to it (extension omitted).
cat > "$appdir/yokan.desktop" <<'DESKTOP'
[Desktop Entry]
Type=Application
Name=Yokan
Comment=Manga, anime and novel library
Exec=Yokan
Icon=yokan
Terminal=false
Categories=AudioVideo;Graphics;
DESKTOP

cat > "$appdir/AppRun" <<'APPRUN'
#!/bin/sh
here=$(dirname "$(readlink -f "$0")")
exec "$here/usr/bin/Yokan" "$@"
APPRUN
chmod +x "$appdir/AppRun"

appimagetool=${APPIMAGETOOL:-}
if [[ -z "$appimagetool" ]]; then
  appimagetool="$work/appimagetool"
  url="https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$arch.AppImage"
  curl -fsSL "$url" -o "$appimagetool"
  chmod +x "$appimagetool"
fi

mkdir -p "$(dirname "$out")"
# --appimage-extract-and-run: GitHub runners have no FUSE, so the tool cannot mount itself.
ARCH="$arch" "$appimagetool" --appimage-extract-and-run "$appdir" "$out"
