#!/usr/bin/env bash
# Launch a locally-built Chanora desktop bundle.
#
# Set CHANORA_BUNDLE_FLAVOUR=debug to point at the debug bundle,
# anything else (or unset) selects the release bundle. The Flutter
# app expects libchanora_bridge.so on the dynamic linker search
# path; this script copies the latest release cdylib into the
# bundle's lib/ if it isn't there yet.

set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
FLAVOUR="${CHANORA_BUNDLE_FLAVOUR:-release}"
BUNDLE="$HERE/apps/chanora_flutter/build/linux/x64/$FLAVOUR/bundle"

if [[ ! -x "$BUNDLE/chanora_flutter" ]]; then
    echo "error: Flutter bundle not built. Run:" >&2
    echo "  (cd apps/chanora_flutter && flutter build linux --$FLAVOUR)" >&2
    exit 1
fi
if [[ ! -e "$BUNDLE/lib/libchanora_bridge.so" ]]; then
    if [[ -e "$HERE/target/$FLAVOUR/libchanora_bridge.so" ]]; then
        cp "$HERE/target/$FLAVOUR/libchanora_bridge.so" "$BUNDLE/lib/"
    else
        echo "error: libchanora_bridge.so missing from $BUNDLE/lib/." >&2
        echo "Run:  cargo build --$FLAVOUR -p chanora_bridge" >&2
        echo "Then: cp target/$FLAVOUR/libchanora_bridge.so $BUNDLE/lib/" >&2
        exit 1
    fi
fi

export LD_LIBRARY_PATH="$BUNDLE/lib:${LD_LIBRARY_PATH:-}"

exec "$BUNDLE/chanora_flutter" "$@"
