#!/usr/bin/env bash
# nolid -- prevent device suspend on lid close

. lib.bash || exit

hold="${XDG_RUNTIME_DIR?}/nolid.hold"

usage() {
	echo "Usage: $progname -h|-r|<command>"
	echo
	echo_opt "-h"	"hold (fork into background instead of running a command)"
	echo_opt "-r"	"release existing hold"
	echo_opt "-u"	"unhold (alias for -r)"
}

name="nolid"
if [[ -t 0 ]]; then
	tty=$(tty)
	name="$name on ${tty#/dev/}"
fi

while getopts :hru OPT; do
	case $OPT in
	h)
		debug "creating lockfile \"$hold\""
		touch "$hold"
		spawn -dc nolid inotifywait -qqe delete_self "$hold" &
		echo "Held."
		exit;;
	r|u)
		debug "deleting lockfile \"$hold\""
		rm -f "$hold"
		echo "Released."
		exit;;
	*) lib:die_getopts;;
	esac
done; shift $((OPTIND-1))

(( $# )) || set -- ac-wait

if [[ -t 0 ]]; then
	settitle "nolid: $1"
fi

systemd-inhibit --who="$name" \
	--what="sleep:handle-lid-switch" \
	--why="Manually inhibited" \
gnome-inhibit --always \
	--who="$name" \
	--what="suspend" \
	--why="Manually inhibited" \
env \
	LVL="$_lvl" \
	_NOLID="1" \
	"$@"
