#!/bin/sh
# launchctl on iOS 6 can return zero even when its IPC connection failed.
# Verify the exact job in GetJobs, which uses an independent Mach interface.
set -eu
label=fr.lightningdocklegacy.routebridge
plist=/Library/LaunchDaemons/fr.lightningdocklegacy.routebridge.plist

registered() {
    jobs=$(/bin/launchctl list) || return 2
    printf '%s\n' "$jobs" | (
        read -r pid status job rest || exit 2
        if [ "$pid" != PID ] || [ "$status" != Status ] || [ "$job" != Label ]; then
            exit 2
        fi
        while read -r pid status job rest; do
            if [ "$job" = "$label" ]; then exit 0; fi
        done
        exit 1
    )
}

state=0
registered || state=$?
if [ "$state" -gt 1 ]; then
    echo "6LightningDock: unable to read the iOS service list." >&2
    exit 1
fi
case "${1:-}" in
    start)
        if [ "$state" -eq 0 ]; then exit 0; fi
        /bin/launchctl load "$plist"
        if ! registered; then
            echo "6LightningDock: service not registered; reboot and retry package configuration in Cydia." >&2
            exit 1
        fi
        ;;
    stop)
        if [ "$state" -eq 1 ]; then exit 0; fi
        /bin/launchctl unload "$plist"
        state=0
        registered || state=$?
        if [ "$state" -ne 1 ]; then
            echo "6LightningDock: service shutdown was not confirmed; restoration cancelled." >&2
            exit 1
        fi
        ;;
    *) echo "Usage: 6ld-service start|stop" >&2; exit 2;;
esac
