#!/bin/sh
# AppRun for the portable muSRFlow ROOT + musrfit runtime AppImage.
#
# The runtime lives in usr/lib/musrflow-runtime inside the image. With no
# arguments (or --help) the launcher explains itself, --install copies the tree
# onto the host (default /opt/musrflow/runtime, where the muSRFlow app searches
# for it), --prefix prints the in-image prefix, and any other first argument is
# treated as a bundled tool name to run.
set -eu

# Resolve this script's directory wherever the AppImage is mounted.
self="$0"
case "$self" in
  /*) ;;
  *) self="$(pwd)/$self" ;;
esac
here="$(cd "$(dirname "$self")" && pwd)"
prefix="$here/usr/lib/musrflow-runtime"

usage() {
  cat <<EOF
muSRFlow portable ROOT + musrfit runtime

Usage:
  $(basename "$0") --install [DIR]   Install the runtime (default: /opt/musrflow/runtime)
  $(basename "$0") --prefix          Print the in-image runtime prefix
  $(basename "$0") <tool> [args...]  Run a bundled tool (for example musrfit, musrt0)
  $(basename "$0")                   Show this help

Custom install location: set MUSRFLOW_RUNTIME_ROOT when launching muSRFlow, or
pass a directory to --install.
EOF
}

if [ "$#" -eq 0 ]; then
  usage
  exit 0
fi

case "$1" in
  --help|-h)
    usage
    exit 0
    ;;
  --prefix)
    echo "$prefix"
    exit 0
    ;;
  --install)
    target="${2:-/opt/musrflow/runtime}"
    mkdir -p "$target"
    cp -a "$prefix/." "$target/"
    echo "Installed muSRFlow runtime to $target"
    exit 0
    ;;
esac

tool="$1"
shift
export ROOTSYS="$prefix"
export MUSRFITPATH="$prefix"
export LD_LIBRARY_PATH="$prefix/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
exec "$prefix/bin/$tool" "$@"
