#!/bin/sh
# configversion: 1

# This hook goal is to return a non zero exit code if the device
# should wait before going to suspension

. "$(which sxmo_common.sh)"

exit_should_wait() {
	sxmo_log "$*"
	printf %s "$1"
	exit 1
}

modem_use() {
	(pgrep -f sxmo_modem.sh > /dev/null || \
		pgrep -f sxmo_mms.sh > /dev/null || \
		pgrep -f mmcli > /dev/null || \
		pgrep -f mmsctl > /dev/null || \
		pgrep -f sxmo_modemsendsms.sh > /dev/null || \
		sxmo_daemons.sh running modem_nocrust || \
		pgrep -f sxmo_modemdaemons.sh >/dev/null) && exit_should_wait "modem"
}

active_ssh() {
	(netstat | grep ESTABLISHED | grep -q ssh) && exit_should_wait "ssh"
}

screenlock() {
	pgrep -f sxmo_screenlock.sh >/dev/null && exit_should_wait "screenlock"
}

playing_mpc() {
	command -v mpc > /dev/null || return # no mpc installed

	(mpc status | grep -q '\[playing\]') && exit_should_wait "mpc"
}

photos_processing() {
	pgrep -f postprocess.sh > /dev/null && exit_should_wait "photos processing"
}

auto_suspend() {
	[ -e "$XDG_CACHE_HOME/sxmo/sxmo.nosuspend" ] && exit_should_wait "auto_suspend_off"
}

modem_use
playing_mpc
screenlock
photos_processing
auto_suspend
active_ssh

exit 0
