#!/bin/sh

set -x

TARGET_VOLUME=${3:-/}
if test "$TARGET_VOLUME" = "/"; then
    APP=/Applications/SingTeam.app
else
    APP="$TARGET_VOLUME/Applications/SingTeam.app"
fi
AGENT=/usr/local/bin/singteam-service
SERVICE=io.singteam.client
LOG_FILE=/var/log/singteam/client_pre_install.log

mkdir -p /var/log/singteam/

{
    # The UI is tray-only (LSUIElement); quitting by name is enough and
    # avoids pkill matching unrelated processes.
    osascript -e 'quit app "SingTeam"' || true

    # Upgrades must replace the existing LaunchDaemon configuration. Early
    # builds installed with the bare `singteam` label and SingTeam's socket,
    # so both legacy names are removed here.
    if test -x "$AGENT"; then
        "$AGENT" service stop || true
        "$AGENT" service uninstall || true
    fi

    for job in "$SERVICE" singteam; do
        if test -f "/Library/LaunchDaemons/$job.plist"; then
            launchctl bootout "system/$job" 2>/dev/null || true
            rm -f "/Library/LaunchDaemons/$job.plist"
        fi
    done

    echo "Preinstall complete"
    exit 0 # all good
} &> "$LOG_FILE"
