#!/usr/bin/env bash
# mock-launchctl — stands in for launchctl in install-launchd.sh / peppa-release.sh tests (first
# on PATH as `launchctl`). Same subcommands, messages and exit codes as the real one; state lives
# in $MOCK_LAUNCHCTL_STATE: loaded/<label> (its plist), unloading/<label> (`print` calls left
# until it is gone), calls.log. Like launchd, `bootout` returns before the agent is unloaded:
# it stays visible for $MOCK_LAUNCHCTL_UNLOAD_PRINTS (2) `print` calls, and a `bootstrap` of it
# meanwhile fails with "Bootstrap failed: 5: Input/output error".
# MOCK_LAUNCHCTL_KICKSTART_FAIL=<label> makes `kickstart` of that label fail.
set -uo pipefail
st="${MOCK_LAUNCHCTL_STATE:?MOCK_LAUNCHCTL_STATE is required}"
mkdir -p "$st/loaded" "$st/unloading"
echo "launchctl $*" >> "$st/calls.log"
label() { echo "${1##*/}"; }  # gui/501/<label> → <label>
case "${1:-}" in
  print)
    l=$(label "$2")
    if [[ -f "$st/unloading/$l" ]]; then
      n=$(cat "$st/unloading/$l")
      if (( n <= 0 )); then rm -f "$st/unloading/$l" "$st/loaded/$l"
      else echo $((n - 1)) > "$st/unloading/$l"; echo "$2 = { state = exiting }"; exit 0; fi
    fi
    [[ -f "$st/loaded/$l" ]] || { echo "Bad request." >&2; echo "Could not find service \"$l\" in domain for user gui: ${2#gui/}" >&2; exit 113; }
    echo "$2 = { state = running }" ;;
  bootout)
    l=$(label "$2")
    [[ -f "$st/loaded/$l" && ! -f "$st/unloading/$l" ]] || { echo "Boot-out failed: 113: Could not find specified service" >&2; exit 113; }
    echo "${MOCK_LAUNCHCTL_UNLOAD_PRINTS:-2}" > "$st/unloading/$l" ;;
  bootstrap)
    plist="$3"
    l=$(/usr/bin/sed -n 's:.*<key>Label</key><string>\(.*\)</string>.*:\1:p' "$plist")
    [[ -n "$l" ]] || { echo "Bootstrap failed: 22: Invalid argument" >&2; exit 22; }
    if [[ -f "$st/loaded/$l" ]]; then echo "Bootstrap failed: 5: Input/output error" >&2; exit 5; fi
    cp "$plist" "$st/loaded/$l" ;;
  kickstart)
    l=$(label "${@: -1}")
    [[ -f "$st/loaded/$l" ]] || { echo "Could not find service \"$l\" in domain for user gui" >&2; exit 113; }
    [[ "${MOCK_LAUNCHCTL_KICKSTART_FAIL:-}" == "$l" ]] && { echo "Could not kickstart service \"$l\": 1: Operation not permitted" >&2; exit 1; }
    echo "$l kickstarted" >> "$st/kickstarts.log" ;;
  *) echo "mock-launchctl: unsupported: $*" >&2; exit 64 ;;
esac
