#!/bin/bash
set -u
set -o pipefail
CONTENTS="$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)"
LOGDIR="$HOME/Library/Application Support/KalinExternal"
/bin/mkdir -p "$LOGDIR" || exit 1
if [ "$(/usr/bin/uname -m)" != "arm64" ]; then
    /usr/bin/osascript -e 'display dialog "此外测版适用于 Apple 芯片 Mac（M1 或更新）。" with title "卡林外测" buttons {"好"}'
    exit 1
fi
MAJOR="$(/usr/bin/sw_vers -productVersion | /usr/bin/cut -d . -f 1)"
if [ "$MAJOR" -lt 13 ]; then
    /usr/bin/osascript -e 'display dialog "此版本需要 macOS 13 或更新版本。" with title "卡林外测" buttons {"好"}'
    exit 1
fi
unset PYTHONPATH PYTHONHOME PYTHONSTARTUP DYLD_LIBRARY_PATH DYLD_INSERT_LIBRARIES DOTNET_STARTUP_HOOKS
export PYTHONDONTWRITEBYTECODE=1 MPLBACKEND=Agg
export DOTNET_ROOT="$CONTENTS/MacOS"
export KALIN_PYTHON="$CONTENTS/Resources/python/bin/python3.12"
cd "$CONTENTS/MacOS" || exit 1
if [ "${KALIN_INTERNAL_CONSOLE:-0}" = "1" ]; then
    ./Kalin "$@" 2>&1 | /usr/bin/tee -a "$LOGDIR/launcher.log"
else
    ./Kalin "$@" >> "$LOGDIR/launcher.log" 2>&1
fi
RESULT=$?
if [ "$RESULT" -ne 0 ]; then
    /usr/bin/osascript -e 'display dialog "卡林启动失败，请运行同目录的终端调试.command。日志位于 ~/Library/Application Support/KalinExternal/launcher.log。" with title "卡林外测" buttons {"好"}'
fi
exit "$RESULT"
