#!/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_post_install.log

mkdir -p /var/log/singteam/
mkdir -p /usr/local/bin/

{
    echo "Installing SingTeam..."

    if test -d "$APP"; then
        echo "SingTeam app copied successfully."
    else
        echo "SingTeam app could not be copied to the Applications folder."
        exit 1
    fi

    ln -sfn "$APP/Contents/MacOS/singteam-service" "$AGENT"
    if test -x "$AGENT"; then
        echo "SingTeam service binary linked successfully."
    else
        echo "SingTeam could not create symlink to /usr/local/bin"
        exit 1
    fi

    # Explicit paths keep SingTeam from colliding with a co-installed
    # SingTeam: default SingTeam uses /var/run/singteam.sock and /var/lib/singteam.
    if ! "$AGENT" service --service "$SERVICE" install \
        --daemon-addr unix:///var/run/singteam.sock \
        --config /var/lib/singteam/default.json \
        --log-file /var/log/singteam/client.log; then
        echo "SingTeam service installation failed."
        exit 1
    fi

    # macOS 26+ intermittently fails `launchctl load` during install with
    # "5: Input/output error" although the plist was written. Fall back to an
    # explicit bootstrap instead of failing the whole install.
    if ! "$AGENT" service --service "$SERVICE" start; then
        echo "service start via the service manager failed; falling back to launchctl bootstrap."
        launchctl enable "system/$SERVICE" 2>&1 || true
        if ! launchctl bootstrap system "/Library/LaunchDaemons/$SERVICE.plist" 2>&1; then
            launchctl kickstart -k "system/$SERVICE" 2>&1 || true
        fi
    fi
    sleep 2
    if launchctl print "system/$SERVICE" 2>/dev/null | grep -q "state = running"; then
        echo "SingTeam service is running under launchd."
    else
        echo "SingTeam service is NOT running after install; launchd says:"
        launchctl print "system/$SERVICE" 2>&1 | head -20
        echo "Hint: System Settings > General > Login Items & Extensions > Allow in the Background must allow SingTeam."
        # Not fatal: the app shows "service not running" and the repair command.
    fi

    open "$APP" || true

    echo "Finished SingTeam installation successfully"
    exit 0 # all good
} &> "$LOG_FILE"
