#!/bin/sh cfpid="${XDG_RUNTIME_DIR:-${TMPDIR:-/tmp}}/caffeine.pid" usage() { cat <<- EOF Usage: ${0##*/} [ -s ] [ -t timeout ] Keep your computer awake Options: -s silent or quiet mode -t <timeout in minutes> EOF } note() { command -v notify-send > /dev/null && notify-send " caffeine" "$1" } die() { note "err: $1" printf "\033[31;1merr: %b\033[0m\n" "$1" 1>&2 exit "${2:-1}" } dep_check() { : "${1:?}" for dep; do command -v "$dep" > /dev/null || die "${dep} not installed" done unset dep } set_menu() { if [ -n "$WAYLAND_DISPLAY" ]; then menu="bemenu" elif [ -n "$DISPLAY" ]; then menu="dmenu" else die "can't be ran from tty, setup xorg or wayland" fi } caf_time() { dep_check "$menu" time="$(printf "1m\n3m\n5m\n10m\n15m\n30m" | "$menu" -p " sleep after ")" echo "${time%m}" } drink() { # usage: drink <time in mins> : "${1:?}" dep_check swayidle brightnessctl swaylock [ -s "$cfpid" ] && kill "$(cat "$cfpid")" swayidle \ timeout "$(($1 - 10))" "brightnessctl --save; brightnessctl set 10%-" \ resume "brightnessctl --restore" \ timeout "$(($1 - 5))" "swaylock" \ timeout "$1" "swaymsg --type command 'output * dpms off'" \ resume "swaymsg --type command 'output * dpms on'" & echo $! > "$cfpid" [ "$silent" != true ] && note "$(uname -n) will sleep after $(($1 / 60)) m of inactivity" } ######## # MAIN # ######## timeout= silent= menu= set_menu while getopts "t:sh" f; do case "$f" in t) timeout="$OPTARG" ;; s) silent=true ;; h) usage exit ;; ?) printf "try '%s -h' for more information\n" "${0##*/}" exit 1 ;; esac done [ -z "$timeout" ] && timeout="$(caf_time)" [ -z "$timeout" ] && exit 1 [ "$((timeout))" -le 0 ] && die "invalid input time" drink "$((timeout * 60))"