#!/bin/sh
# Install the Timmy tick timer on macOS via launchd.
# Usage: ./deploy/install-mac-timer.sh
set -e

PROJECT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
PLIST_SRC="$PROJECT_DIR/deploy/com.timmy.tick.plist"
PLIST_DST="$HOME/Library/LaunchAgents/com.timmy.tick.plist"
LABEL="com.timmy.tick"

# Ensure data dir exists for logs
mkdir -p "$PROJECT_DIR/data"

# Make wrapper executable
chmod +x "$PROJECT_DIR/deploy/timmy-tick-mac.sh"

# Unload if already installed
if launchctl list "$LABEL" >/dev/null 2>&1; then
    echo "Unloading existing $LABEL..."
    launchctl bootout "gui/$(id -u)/$LABEL" 2>/dev/null || true
fi

# Fill in project path and install
sed "s|__PROJECT_DIR__|$PROJECT_DIR|g" "$PLIST_SRC" > "$PLIST_DST"

# Load
launchctl bootstrap "gui/$(id -u)" "$PLIST_DST"

echo "Installed! Timmy will tick every 5 minutes."
echo "  Logs: $PROJECT_DIR/data/tick.log"
echo "  Check: launchctl list | grep timmy"
echo "  Stop:  launchctl bootout gui/\$(id -u)/com.timmy.tick"
