#!/bin/bash
# Toggle idle inhibit via systemd-inhibit (hypridle respects the logind idle hint).
# The PID file tracks the background sleep process used to hold the inhibitor lock.
PID_FILE="/tmp/caffeine-inhibit.pid"

# kill -0 sends no signal; it just checks whether the process is still alive.
# If the PID file exists and the process is running, caffeine is active → turn it off.
if [[ -f "$PID_FILE" ]] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
    # Killing the sleep process releases the systemd-inhibit lock automatically.
    kill "$(cat "$PID_FILE")"
    rm -f "$PID_FILE"
    notify-send -t 2000 "Caffeine" "Idle inhibit OFF"
else
    # --what=idle: block the logind idle-inhibit slot that hypridle watches.
    # --mode=block: the inhibitor stays active for the lifetime of the command.
    # "sleep infinity" is the sentinel process whose PID we save.
    systemd-inhibit --what=idle \
        --who="caffeine" \
        --why="Caffeine mode active" \
        --mode=block \
        sleep infinity &
    # $! is the PID of the most recently backgrounded process (sleep infinity above).
    echo $! > "$PID_FILE"
    notify-send -t 2000 "Caffeine" "Idle inhibited"
fi
