#!/bin/bash
# Compila Mac Commander e crea l'app. Con "install" la copia in /Applications.
# La build sta fuori dal NAS: su una cartella SMB il compilatore non riesce a rinominare i file.
set -euo pipefail
cd "$(dirname "$0")"

SCRATCH="$HOME/Library/Caches/MacCommander-build"
swift build -c release --scratch-path "$SCRATCH"

APP="$SCRATCH/Mac Commander.app"
rm -rf "$APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
cp "$SCRATCH/release/MacCommander" "$APP/Contents/MacOS/"
cp Support/Info.plist "$APP/Contents/"
if [ -f Support/AppIcon.icns ]; then
    cp Support/AppIcon.icns "$APP/Contents/Resources/"
    /usr/libexec/PlistBuddy -c "Add :CFBundleIconFile string AppIcon" "$APP/Contents/Info.plist"
fi

# Firma stabile: così macOS ricorda i permessi (cartelle, disco) tra una build e l'altra.
# Con un certificato "Developer ID Application" si usa quello (serve per la notarizzazione).
if [ -z "${SIGN_IDENTITY:-}" ] && security find-identity -v -p codesigning | grep -q "Developer ID Application"; then
    SIGN_IDENTITY="Developer ID Application"
fi
IDENTITY="${SIGN_IDENTITY:-Apple Development}"
codesign --force --options runtime --sign "$IDENTITY" "$APP" 2>/dev/null || codesign --force --sign - "$APP"

if [ "${1:-}" = "install" ]; then
    pkill -x MacCommander 2>/dev/null || true
    rm -rf "/Applications/Mac Commander.app"
    cp -R "$APP" /Applications/
    echo "Installata in /Applications/Mac Commander.app"
else
    echo "Creata: $APP"
fi
