#!/bin/bash
# freeslapmac-silent — switch between the loud and silent builds.
# Only one may run at a time: both write /tmp/freeslapmac_cmd, and each launch kills
# every spank process it can find.
#
# Usage: bash switch.sh silent | loud

set -uo pipefail

LOUD="${LOUD_APP:-/Applications/FreeSlapMac.app}"
SILENT="${SILENT_APP:-/Applications/FreeSlapMac Silent.app}"

case "${1:-}" in
  silent) TARGET="$SILENT" ;;
  loud)   TARGET="$LOUD" ;;
  *)      echo "usage: bash switch.sh silent|loud" >&2; exit 2 ;;
esac

[ -d "$TARGET" ] || { echo "not installed: $TARGET" >&2; echo "build it first: bash build.sh" >&2; exit 1; }

# Quit politely so the app can tear down its root wrapper (a hard kill leaves it running).
osascript -e 'quit app "FreeSlapMac Silent"' >/dev/null 2>&1
osascript -e 'quit app "FreeSlapMac"' >/dev/null 2>&1
for _ in 1 2 3 4 5 6; do pgrep -x FreeSlapMac >/dev/null 2>&1 || break; sleep 0.5; done
if pgrep -x FreeSlapMac >/dev/null 2>&1; then
  echo "FreeSlapMac is still running — quit it manually, then re-run this." >&2
  exit 1
fi

open -a "$TARGET"
echo "launched: $TARGET"
