#!/bin/bash
# FileWave macOS upgrade fileset - PREFLIGHT script.
#
# Why this exists
# ---------------
# An in-place client upgrade overlays new files but never deletes anything, so
# files from the previous version survive inside the signed app bundles (old
# flutter_assets in FileWave Kiosk.app/Contents/Frameworks/App.framework, old Qt
# plugins in fwGUI.app, ...). Any extra file inside a sealed bundle makes
# Gatekeeper reject the whole app:
#     /usr/local/sbin/FileWave.app: a sealed resource is missing or invalid
#     In subcomponent: .../FileWave Kiosk.app/Contents/Frameworks/App.framework
#
# Re-signing the fileset cannot fix this: the leftovers belong to the machine,
# not to the fileset. They have to be removed on the client.
#
# What it removes, and why only this
# ----------------------------------
# Only the two nested application bundles. The upgrade fileset carries both of
# them complete - checked against every CodeResources seal in each shipped
# archive from 15.4.2 to 16.4.0, with no sealed resource missing - so activation
# restores a pristine copy and no stale file can survive. Neither bundle is
# needed by fwcld to keep running and complete the upgrade.
#
# It deliberately does not touch fwcld, the Qt frameworks in
# /Library/Frameworks/FileWaveCore.framework, or anything else under
# FileWave.app. Preflight runs before the fileset is downloaded, so the machine
# may still need to run the old client for some time, including across a reboot.
#
# Always exits 0: a non-zero preflight result aborts fileset installation, and
# a cleanup problem must not block the upgrade intended to repair the signature.

set -u

APP="/usr/local/sbin/FileWave.app"
KIOSK="$APP/Contents/MacOS/FileWave Kiosk.app"
FWGUI="$APP/Contents/Resources/fwGUI.app"

log() {
    echo "fw-preflight-clean: $*"
    /usr/bin/logger -t fw-preflight-clean "$*" 2>/dev/null || true
}

if [ ! -d "$APP" ]; then
    log "no $APP on this machine (fresh install) - nothing to clean"
    exit 0
fi

for bundle in "$KIOSK" "$FWGUI"; do
    if [ ! -e "$bundle" ] && [ ! -L "$bundle" ]; then
        log "not present, nothing to do: $bundle"
        continue
    fi

    /bin/rm -rf "$bundle"

    # Check the end state rather than rm's exit code: a partial removal is what
    # would leave the bundle broken, and that is what has to be reported.
    if [ -e "$bundle" ] || [ -L "$bundle" ]; then
        log "WARNING could not completely remove $bundle - stale files may remain"
    else
        log "removed $bundle (the fileset reinstalls it complete)"
    fi
done

log "preflight cleanup done"
exit 0
