#!/bin/bash
# Nmonic Launcher Wrapper - Persists permissions and code signing across rebuilds

LATEST_BINARY="/Users/dobby/Documents/GitHub/nmonic/.claude/worktrees/romantic-noyce/.build/release/Nmonic"
FALLBACK_BINARY="/Applications/Nmonic.app/Contents/MacOS/Nmonic.bin"
APP_BUNDLE="/Applications/Nmonic.app"

# Function to code-sign the app bundle
code_sign_app() {
    codesign -s - "$APP_BUNDLE" --deep --force 2>/dev/null
    return $?
}

# If latest binary exists and is newer than fallback, update it
if [ -f "$LATEST_BINARY" ]; then
    if [ ! -f "$FALLBACK_BINARY" ] || [ "$LATEST_BINARY" -nt "$FALLBACK_BINARY" ]; then
        # Update the fallback binary with the latest build
        cp "$LATEST_BINARY" "$FALLBACK_BINARY" 2>/dev/null
        # Code-sign the app bundle to maintain permission cache
        code_sign_app
    fi
    # Execute the latest binary
    exec "$LATEST_BINARY" "$@"
elif [ -f "$FALLBACK_BINARY" ]; then
    # Execute fallback if latest doesn't exist
    exec "$FALLBACK_BINARY" "$@"
else
    echo "Error: Nmonic binary not found"
    exit 1
fi
