#!/bin/bash
# SleepToggle installer — https://sleep.138.dk
# Compiles a tiny menu bar app on YOUR Mac (no prebuilt binary, no Gatekeeper
# fuss), adds a sudo rule scoped to exactly `pmset -a disablesleep 1|0`,
# and registers it to start at login. Uninstall: /uninstall.sh on the same host.
set -euo pipefail
BASE="https://sleep.138.dk"
APP="$HOME/Applications/SleepToggle.app"
BIN="$APP/Contents/MacOS/SleepToggle"
LABEL="com.sleeptoggle"
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
ME="$(id -un)"
[ "$(uname)" = "Darwin" ] || { echo "SleepToggle is macOS-only."; exit 1; }
if ! xcode-select -p >/dev/null 2>&1; then
echo "SleepToggle compiles on your Mac, which needs Apple's Command Line Tools (a one-time install)."
echo "→ opening Apple's installer dialog now — re-run this command once it finishes."
xcode-select --install >/dev/null 2>&1 || true
exit 1
fi
TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT
echo "→ downloading source ($BASE/SleepToggle.swift)"
curl -fsSL "$BASE/SleepToggle.swift" -o "$TMP/SleepToggle.swift"
echo "→ compiling into ~/Applications/SleepToggle.app"
mkdir -p "$APP/Contents/MacOS"
cat > "$APP/Contents/Info.plist" <<'EOF'
CFBundleIdentifiercom.sleeptoggle
CFBundleNameSleepToggle
CFBundleExecutableSleepToggle
CFBundlePackageTypeAPPL
LSUIElement
EOF
swiftc -O "$TMP/SleepToggle.swift" -o "$BIN"
echo "→ sudo rule: lets your user run EXACTLY 'pmset -a disablesleep 1' and"
echo " 'pmset -a disablesleep 0' without a password — nothing else."
echo " (That's what your password is needed for now.)"
printf '%s ALL=(ALL) NOPASSWD: /usr/bin/pmset -a disablesleep 1, /usr/bin/pmset -a disablesleep 0\n' "$ME" > "$TMP/sudoers"
sudo visudo -c -f "$TMP/sudoers" >/dev/null
sudo install -m 440 -o root -g wheel "$TMP/sudoers" /etc/sudoers.d/pmset-disablesleep
sudo -k # drop cached credentials so the next line truly tests the NOPASSWD rule
sudo -n /usr/bin/pmset -a disablesleep 0 >/dev/null
echo " rule verified"
echo "→ registering start-at-login (LaunchAgent $LABEL)"
mkdir -p "$HOME/Library/LaunchAgents"
cat > "$PLIST" <
Label$LABEL
ProgramArguments$BIN
RunAtLoad
EOF
echo "→ launching"
launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
pkill -x SleepToggle 2>/dev/null || true
launchctl bootstrap "gui/$(id -u)" "$PLIST"
echo "✓ installed — look for ☾ in your menu bar."
echo " ☾ = normal sleep · ☕ = sleep disabled"
echo " uninstall: curl -fsSL $BASE/uninstall.sh | bash"