#!/usr/bin/env bash
# Install lidcreak: makes FreeSlapMac's "Lid Creaking Sound" switch real.
# No root needed. Re-runnable (upgrades in place).
set -euo pipefail

BUNDLE="com.devesh.freeslapmac"
LABEL="${LIDCREAK_LABEL:-com.isaac.lidcreak}"
SRC="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEST="$HOME/Library/Application Support/FreeSlapLidCreak"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
LOGDIR="$HOME/Library/Logs"
APP="${FREESLAP_APP:-}"

say() { printf '\033[1m%s\033[0m\n' "$*"; }
ok()  { printf '  \033[32m✓\033[0m %s\n' "$*"; }
bad() { printf '  \033[31m✗\033[0m %s\n' "$*"; }

say "lidcreak installer"

# 1. FreeSlapMac present?
if [ -z "$APP" ]; then
  for c in "/Applications/FreeSlapMac.app" "$HOME/Applications/FreeSlapMac.app"; do
    [ -d "$c" ] && APP="$c" && break
  done
fi
if [ -z "$APP" ] || [ ! -d "$APP" ]; then
  bad "FreeSlapMac.app not found — install the free app first (github.com/ibedevesh/freeslapmac)."
  exit 1
fi
ok "app: $APP"

CREAK="$APP/Contents/Resources/Sounds/creaking.mp3"
if [ ! -f "$CREAK" ]; then
  bad "missing $CREAK — the sound asset ships with the app; reinstall FreeSlapMac."
  exit 1
fi
ok "sound: creaking.mp3 ($(wc -c <"$CREAK" | tr -d ' ') bytes)"

# 2. Python 3 (macOS ships one; Command Line Tools are enough)
if ! command -v python3 >/dev/null 2>&1; then
  bad "python3 not found — run: xcode-select --install"
  exit 1
fi
ok "python3: $(python3 -V 2>&1)"

# 3. Copy the helper out of the read-only download location
mkdir -p "$DEST" "$HOME/Library/LaunchAgents" "$LOGDIR"
install -m 0755 "$SRC/lidcreak.py" "$DEST/lidcreak.py"
ok "installed: $DEST/lidcreak.py"

# 4. LaunchAgent (user-level, starts at login, restarts if it dies)
launchctl bootout "gui/$(id -u)/$LABEL" >/dev/null 2>&1 || true
cat > "$PLIST" <<PLISTEOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key><string>$LABEL</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/bin/python3</string>
    <string>$DEST/lidcreak.py</string>
    <string>--app</string>
    <string>$APP</string>
  </array>
  <key>RunAtLoad</key><true/>
  <key>KeepAlive</key><true/>
  <key>ThrottleInterval</key><integer>5</integer>
  <key>StandardOutPath</key><string>$LOGDIR/lidcreak.out.log</string>
  <key>StandardErrorPath</key><string>$LOGDIR/lidcreak.err.log</string>
</dict>
</plist>
PLISTEOF
plutil -lint "$PLIST" >/dev/null
ok "LaunchAgent: $PLIST"

# 5. Make sure the in-app switch reads ON (the app writes this pref itself)
defaults write "$BUNDLE" _creakingEnabled -bool true
ok "FreeSlapMac toggle '_creakingEnabled' = true"

# 6. Load it
if launchctl bootstrap "gui/$(id -u)" "$PLIST" 2>/dev/null; then
  ok "agent bootstrapped"
else
  launchctl unload "$PLIST" >/dev/null 2>&1 || true
  launchctl load -w "$PLIST"
  ok "agent loaded (legacy load -w)"
fi

sleep 1

# 7. Prove it: sensor read + one creak through the speakers
echo
say "self-test"
python3 "$DEST/lidcreak.py" --app "$APP" --self-test || {
  echo
  bad "the sensor did not answer. This Mac may not expose a lid-angle sensor"
  bad "(it exists on Apple Silicon MacBooks). The agent stays installed but idle."
  exit 2
}

echo
say "done"
cat <<EOF
  Tilt the screen slowly — you should hear the creak, and the log should show it:
      tail -f ~/Library/Logs/lidcreak.log
  Turn it off any time with FreeSlapMac's own "Lid Creaking Sound" switch,
  or remove everything with:  bash "$SRC/uninstall.sh"
EOF
