#!/bin/bash
# Crystool for Mac: starts the private Python that setup-mac.command made in the Crystool folder (no Terminal window).
HERE="$(cd "$(dirname "$0")/../../.." 2>/dev/null && pwd)"
CFG="$HOME/Library/Application Support/Crystool/install-path.txt"
if [ ! -x "$HERE/.venv/bin/python" ] || [ ! -d "$HERE/crystool" ]; then
  ALT="$(cat "$CFG" 2>/dev/null)"
  if [ -n "$ALT" ] && [ -x "$ALT/.venv/bin/python" ] && [ -d "$ALT/crystool" ]; then HERE="$ALT"; fi
fi
if [ ! -x "$HERE/.venv/bin/python" ] || [ ! -d "$HERE/crystool" ]; then
  /usr/bin/osascript -e 'display dialog "Crystool is not set up yet.

Open the Crystool folder and double-click  setup-mac.command  (one time, needs internet). See INSTALL-mac.txt." buttons {"OK"} default button 1 with title "Crystool" with icon caution' >/dev/null 2>&1
  exit 1
fi
cd "$HERE" || exit 1
LOGD="$HOME/Library/Logs"; mkdir -p "$LOGD" 2>/dev/null; LOG="$LOGD/Crystool.log"
if [ -f "$LOG" ] && [ "$(stat -f%z "$LOG" 2>/dev/null || echo 0)" -gt 5000000 ]; then mv -f "$LOG" "$LOG.old"; fi
echo "=== $(date) start $HERE" >> "$LOG" 2>/dev/null
PY="$HERE/.venv/bin/Crystool"; [ -x "$PY" ] || PY="$HERE/.venv/bin/python"
exec "$PY" -m crystool "$@" >> "$LOG" 2>&1
