#!/bin/sh
# Stable compatibility path for existing desktop-installed zn shortcuts.
# Use the persistent Go installation after desktop verifies and activates it.
# Node remains available before activation and for explicit rollback.

set -e

# Follow symlinks so we work whether the user invokes /usr/local/bin/zen
# (a symlink) or the resource path directly.
SOURCE="$0"
while [ -h "$SOURCE" ]; do
  TARGET="$(readlink "$SOURCE")"
  case "$TARGET" in
    /*) SOURCE="$TARGET" ;;
    *)  SOURCE="$(dirname "$SOURCE")/$TARGET" ;;
  esac
done
SCRIPT_DIR="$(cd "$(dirname "$SOURCE")" && pwd)"

# Find the Electron executable. Try the macOS layout first (script lives
# in Contents/Resources, executable in Contents/MacOS), then the Linux
# layout (script in resources/, executable in the parent).
APP_BUNDLE="$(cd "$SCRIPT_DIR/.." && pwd)"
ELECTRON=""
if [ -d "$APP_BUNDLE/MacOS" ]; then
  for candidate in "$APP_BUNDLE/MacOS"/*; do
    if [ -x "$candidate" ]; then
      ELECTRON="$candidate"
      break
    fi
  done
fi
if [ -z "$ELECTRON" ]; then
  # Linux unpacked: <root>/<exe> with <root>/resources/zen
  for candidate in "$APP_BUNDLE"/zennotes "$APP_BUNDLE"/ZenNotes "$APP_BUNDLE"/zen-notes; do
    if [ -x "$candidate" ]; then
      ELECTRON="$candidate"
      break
    fi
  done
fi
case "${ZENNOTES_CLI_ENGINE:-go}" in
  go)
    : "${ZENNOTES_WORKSPACE_SOURCE:=app}"
    export ZENNOTES_WORKSPACE_SOURCE
    if [ -d "$APP_BUNDLE/MacOS" ]; then
      DEFAULT_USER_DATA="$HOME/Library/Application Support/ZenNotes"
    else
      DEFAULT_USER_DATA="${XDG_CONFIG_HOME:-$HOME/.config}/ZenNotes"
    fi
    USER_DATA="${ZENNOTES_USER_DATA_PATH:-${ZENNOTES_CONFIG_DIR:-$DEFAULT_USER_DATA}}"
    if [ -z "${ZENNOTES_APP_PATH:-}" ] && [ -n "$ELECTRON" ]; then
      ZENNOTES_APP_PATH="${APPIMAGE:-$ELECTRON}"
      export ZENNOTES_APP_PATH
    fi
    if [ -x "$USER_DATA/cli/zn" ]; then exec "$USER_DATA/cli/zn" "$@"; fi
    ;;
  legacy) ;;
  *) echo "zn: ZENNOTES_CLI_ENGINE must be go or legacy." >&2; exit 2 ;;
esac

if [ -z "$ELECTRON" ]; then
  echo "zn: could not locate the ZenNotes Electron binary near $APP_BUNDLE" >&2
  exit 2
fi

CLI_JS="$SCRIPT_DIR/cli.js"
if [ ! -f "$CLI_JS" ]; then
  echo "zn: cli.js not found next to wrapper at $CLI_JS" >&2
  exit 2
fi

ELECTRON_RUN_AS_NODE=1 exec "$ELECTRON" "$CLI_JS" "$@"
