#!/bin/sh
# Starts Equilevel (macOS): the local server in the background, then ends at once. Every double-click opens a new
# window; the server stops by itself when no window is open any more.
# Messages and errors: ~/Library/Application Support/Equilevel/equilevel.log

APP="$(cd "$(dirname "$0")/../.." && pwd -P)"
RES="$APP/Contents/Resources/Equilevel"

# Started straight from Downloads, macOS moves the app to a read-only random place ("App Translocation").
case "$APP" in
  */AppTranslocation/*)
    /usr/bin/osascript -e 'display dialog "Please move Equilevel into your Applications folder first, then open it from there." with title "Equilevel" buttons {"OK"} default button 1 with icon caution' >/dev/null 2>&1
    exit 1
    ;;
esac

# "Open Anyway" applies to the bundle, but the embedded programs (Python, FFmpeg, the numpy and scipy libraries)
# carry the quarantine mark each and would be blocked one by one.
/usr/bin/xattr -dr com.apple.quarantine "$APP" 2>/dev/null

if [ "$(/usr/sbin/sysctl -n hw.optional.arm64 2>/dev/null)" = "1" ]; then
  PY="$RES/python-arm64/bin/python3.12"
else
  PY="$RES/python-x86_64/bin/python3.12"
fi

DATA="$HOME/Library/Application Support/Equilevel"
/bin/mkdir -p "$DATA"
cd "$RES" || exit 1
# -E -s: no PYTHON* variables and no packages from the user folder – exactly the bundled Python with exactly this
# code. -u: redirected into a file, Python would buffer and the log stay empty while the server runs.
nohup "$PY" -E -s -u -X utf8 "$RES/equilevel.py" >>"$DATA/equilevel.log" 2>&1 </dev/null &
exit 0
