summaryrefslogtreecommitdiff
path: root/.local/bin/caffeine
blob: ed4eb8115273c34bf3704484b341fba162882d2b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#!/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="wmenu"
	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:?}"
	disp=

	dep_check swayidle wlr-randr brightnessctl swaylock

	[ -s "$cfpid" ] &&
		kill "$(cat "$cfpid")"

	disp="$(wlr-randr  | grep  -om1 '^[^ ]*')"
	swayidle \
		timeout "$(($1 - 10))" "brightnessctl --save; brightnessctl set 10%-" \
		resume "brightnessctl --restore" \
		timeout "$(($1 - 5))" "swaylock" \
		timeout "$1" "wlr-randr --output ${disp} --off" \
		resume "wlr-randr --output ${disp} --on --adaptive-sync enabled" &
	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))"