#!/bin/bash
#
# walker - reminds you to walk every 45 minutes
# ---
# see: https://github.com/badlogic/walker

INTERVAL_MINS=60
PIDFILE="$HOME/.walker.pid"

notify() {
    osascript -e "display notification \"$1\" with title \"Walker\" sound name \"Glass\""
}

run_daemon() {
    while true; do
        notify "Time to walk! Get up and move for 5 minutes."
        say "Time to walk"
        sleep $((INTERVAL_MINS * 60))
    done
}

stop_daemon() {
    if [[ -f "$PIDFILE" ]]; then
        pid=$(cat "$PIDFILE")
        if kill -0 "$pid" 2>/dev/null; then
            kill "$pid"
            rm -f "$PIDFILE"
            echo "Walker stopped."
        else
            rm -f "$PIDFILE"
            echo "Walker was not running."
        fi
    else
        echo "Walker is not running."
    fi
}

case "${1:-start}" in
    start)
        if [[ -f "$PIDFILE" ]] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
            echo "Walker is already running (PID $(cat "$PIDFILE"))."
            exit 1
        fi
        echo "Starting walker (reminding every ${INTERVAL_MINS} minutes)..."
        run_daemon &>/dev/null &
        echo $! > "$PIDFILE"
        disown
        echo "Walker started in background (PID $!)."
        ;;
    stop)
        stop_daemon
        ;;
    status)
        if [[ -f "$PIDFILE" ]] && kill -0 "$(cat "$PIDFILE")" 2>/dev/null; then
            echo "Walker is running (PID $(cat "$PIDFILE"))."
        else
            echo "Walker is not running."
        fi
        ;;
    *)
        echo "Usage: walker [start|stop|status]"
        exit 1
        ;;
esac
