#!/bin/sh
# TradeBuddy manual upgrade for macOS (standalone, does NOT need the app's own helper).
#
# Why: the in-app auto-replace runs a helper script embedded in the CURRENTLY INSTALLED
# version. If that helper has a bug, a fixed build published later can never help the
# old client. This script is the escape hatch.
#
# Usage:
#   sh manual-upgrade-mac.sh [package.zip] [install-dir]
set -e

PKG="${1:-$HOME/Library/Application Support/tradebuddy/data/updates}"
DEST="${2:-/Applications/TradeBuddy.app}"

if [ -d "$PKG" ]; then
  # no file given -> pick the newest zip in the pending dir
  NEWEST=$(ls -t "$PKG"/*.zip 2>/dev/null | head -1 || true)
  [ -n "$NEWEST" ] || { echo "[tb-upgrade] no update package found in $PKG" >&2; exit 1; }
  PKG="$NEWEST"
fi
[ -f "$PKG" ] || { echo "[tb-upgrade] package not found: $PKG" >&2; exit 1; }
echo "[tb-upgrade] package : $PKG"
echo "[tb-upgrade] install : $DEST"

# 1) stop the app (tray included)
pkill -f "$DEST/Contents/MacOS" 2>/dev/null || true
sleep 2

# 2) extract
STAGE=$(mktemp -d /tmp/tb-upgrade.XXXXXX)
ditto -x -k "$PKG" "$STAGE"
APP=""
for p in "$STAGE"/*.app; do [ -d "$p" ] && APP="$p" && break; done
[ -n "$APP" ] || { echo "[tb-upgrade] no .app inside the package" >&2; exit 1; }

# 3) back up
BAK="$DEST.bak-manual"
rm -rf "$BAK"
mv "$DEST" "$BAK" || { echo "[tb-upgrade] cannot move the current app (run with enough rights)" >&2; exit 1; }

# 4) put the new one in place
mv "$APP" "$DEST" || { mv "$BAK" "$DEST"; echo "[tb-upgrade] install failed, rolled back" >&2; exit 1; }
xattr -dr com.apple.quarantine "$DEST" 2>/dev/null || true
codesign --verify --deep --strict "$DEST" >/dev/null 2>&1 || echo "[tb-upgrade] warning: signature check failed"

# 5) start
rm -rf "$STAGE"
open "$DEST"
echo "[tb-upgrade] done. Backup kept at: $BAK"
