#!/bin/sh
# coa — CoAnimator headless CLI shim.
#
# Resolves the binary relative to its own location so it works regardless of
# where CoAnimator.app is installed, and supports packaged and dev layouts:
#
#   macOS:      .../CoAnimator.app/Contents/Resources/coa  →  ../MacOS/CoAnimator
#   Linux deb:  /opt/CoAnimator/resources/coa         →  ../coanimator
#   AppImage:   $APPDIR/resources/coa                 →  ../coanimator (mount) or $APPIMAGE
#   dev:        <repo>/bin/coa                        →  <repo>/node_modules/.bin/electron <repo>
#
# The menu item "Install coa Command Line Tool…" symlinks this onto PATH
# (typically /usr/local/bin/coa). After that you can run, from any terminal:
#
#   coa render <project> [--preset 1080p30] [--runners 4] [--out path.mp4]
#   coa --help

set -e

# Resolve our own absolute path, following symlinks (so /usr/local/bin/coa
# → bundle Resources/coa works correctly).
SOURCE="$0"
while [ -L "$SOURCE" ]; do
  LINK="$(readlink "$SOURCE")"
  case "$LINK" in
    /*) SOURCE="$LINK" ;;
    *)  SOURCE="$(dirname "$SOURCE")/$LINK" ;;
  esac
done
DIR="$(cd "$(dirname "$SOURCE")" && pwd)"

# Packaged macOS: Contents/Resources/coa → ../MacOS/CoAnimator
if [ -x "$DIR/../MacOS/CoAnimator" ]; then
  exec "$DIR/../MacOS/CoAnimator" --cli "$@"
fi

# Packaged Linux: resources/coa → ../<executable>. electron-builder lowercases
# the executable name on Linux (deb: /opt/CoAnimator/coanimator; same layout
# inside an AppImage mount) — try the productName casing too, in case
# `executableName` is ever set explicitly.
for BIN in "$DIR/../coanimator" "$DIR/../CoAnimator"; do
  if [ -x "$BIN" ]; then
    exec "$BIN" --cli "$@"
  fi
done

# AppImage: when the relative layout is not resolvable (e.g. this shim was
# copied out of the transient squashfs mount), re-launch the AppImage itself.
if [ -n "$APPIMAGE" ] && [ -x "$APPIMAGE" ]; then
  exec "$APPIMAGE" --cli "$@"
fi

# Dev: <repo>/bin/coa → <repo>/node_modules/.bin/electron <repo> --dev
if [ -x "$DIR/../node_modules/.bin/electron" ] && [ -f "$DIR/../electron/main.cjs" ]; then
  exec "$DIR/../node_modules/.bin/electron" "$DIR/.." --dev --cli "$@"
fi

echo "coa: cannot locate CoAnimator binary or dev electron near $DIR" >&2
exit 1
