#!/bin/bash
# Pubblica una nuova versione: ./release.sh 0.2 "Cosa c'è di nuovo"
# Alza il numero di versione, compila, firma, (notarizza se c'è il profilo), crea lo zip
# e lo carica su https://mac-commander.vercel.app insieme a latest.json, che l'app legge
# per sapere se c'è un aggiornamento. Poi commit e tag su GitHub.
set -euo pipefail
cd "$(dirname "$0")"

VERSION="${1:?Uso: ./release.sh <versione> \"novità\"}"
NOTES="${2:-}"
PLIST=Support/Info.plist
SITE_URL="https://mac-commander.vercel.app"
SITE="$HOME/Library/Caches/MacCommander-release/site"   # collegato al progetto Vercel "mac-commander"
NOTARY_PROFILE="mac-commander"                          # xcrun notarytool store-credentials mac-commander …

BUILD=$(( $(/usr/libexec/PlistBuddy -c "Print :CFBundleVersion" "$PLIST") + 1 ))
/usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $VERSION" "$PLIST"
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $BUILD" "$PLIST"
MINOS=$(/usr/libexec/PlistBuddy -c "Print :LSMinimumSystemVersion" "$PLIST")

./build.sh
APP="$HOME/Library/Caches/MacCommander-build/Mac Commander.app"
ZIP="$HOME/Library/Caches/MacCommander-release/MacCommander-$VERSION.zip"
rm -f "$ZIP"
ditto -c -k --keepParent "$APP" "$ZIP"

if xcrun notarytool history --keychain-profile "$NOTARY_PROFILE" >/dev/null 2>&1; then
    echo "Notarizzazione…"
    xcrun notarytool submit "$ZIP" --keychain-profile "$NOTARY_PROFILE" --wait
    xcrun stapler staple "$APP"
    rm -f "$ZIP"
    ditto -c -k --keepParent "$APP" "$ZIP"
else
    echo "Niente notarizzazione (manca il profilo $NOTARY_PROFILE): la prima apertura chiede \"Apri comunque\"."
fi

SHA=$(shasum -a 256 "$ZIP" | cut -d' ' -f1)
mkdir -p "$SITE"
find "$SITE" -maxdepth 1 -name "MacCommander*.zip" -delete
cp "$ZIP" "$SITE/MacCommander-$VERSION.zip"
cp "$ZIP" "$SITE/MacCommander.zip"
sips -s format png -Z 256 Support/AppIcon.icns --out "$SITE/icon.png" >/dev/null
sed -e "s/{{VERSION}}/$VERSION/g" -e "s/{{MINOS}}/$MINOS/g" site/index.html > "$SITE/index.html"
printf '.env*\n.vercel\n.gitignore\n' > "$SITE/.vercelignore"
python3 - "$SITE/latest.json" <<PY
import json, sys
json.dump({"version": "$VERSION", "build": $BUILD, "url": "$SITE_URL/MacCommander-$VERSION.zip",
           "sha256": "$SHA", "notes": """$NOTES""", "minimumSystem": "$MINOS"},
          open(sys.argv[1], "w"), ensure_ascii=False, indent=2)
PY

(cd "$SITE" && vercel deploy --prod --yes >/dev/null)
echo "Pubblicata $VERSION ($BUILD) su $SITE_URL"

git add -A
git commit -q -m "Versione $VERSION" || true
git tag -f "v$VERSION"
git push -q origin HEAD
git push -q -f origin "v$VERSION"
