#! /bin/sh

# upsevent is called by upssched from upssched.conf

# ----------------------------------------------------------------------
# configuration

# off-system account to notify
MAILTO=contact@example.com

# time to allow after logging/warning, before invoking shutdown
FINALDELAY=10

# if this file exists, supress early shutdown
NOEARLYFILE=/etc/nut/noearly

# file containing PID of upslog daemon
UPSLOGPIDFILE=/var/run/nut/upslog.pid

# ----------------------------------------------------------------------
# handle argument

EVENT=$1

# make sure we got an argument
if test -z "$EVENT"; then
	logger -s -t upsevent -i -p daemon.err "Missing argument: UPS event ID"
	exit 1
fi

case "$EVENT" in

# ----------------------------------------------------------------------
online|onbatt|lowbatt|commok|replbatt)

# immediately record UPS statistics on state-change events

# make sure PID file exists to read (might not be running)
if ! test -e "$UPSLOGPIDFILE" ; then
	logger -s -t upsevent -i -p daemon.warn "UPSLOGPIDFILE not found: $UPSLOGPIDFILE"
	exit 1
fi

# get PID of logger process from file
read UPSLOGPID < "$UPSLOGPIDFILE"

# send SIGUSR1 to running upslog(8)
kill -USR1 "$UPSLOGPID"

;;

# ----------------------------------------------------------------------
realout)

MSG="System running on battery power - may shut down with little warning"

# log the extended outage
logger -s -t upsevent -i -p daemon.alert "$MSG"

# warn all users
wall "$MSG"

;;

# ----------------------------------------------------------------------
longbatt)

# Shut down system if running on battery for long.
# This preserves battery runtime for more critical loads.
# Do not use NUT FSD (force shutdown), as that would power down the UPS.
# We just want to take the big load off, and keep UPS running.

# if we want to keep running, we create this file
if test -e "$NOEARLYFILE" ; then
	logger -s -t upsevent -i -p daemon.info "Supressing early shutdown per file"
	exit
fi

MSG="Shuting down system due to amount of time on battery power"

# log shutdown, *.panic will also broadcast to all users
logger -s -t upsevent -i -p daemon.panic "$MSG"

# send mail about the shutdown
mail -s "Power outage shutdown" "$MAILTO" <<EOM
$MSG
Host: $(hostname)
Date: $(date)
EOM

# allow time for mail to go through, and last-second user actions
sleep $FINALDELAY

# suspend-to-disk
sudo -n s2disk

# Allow time for snapshot to happen, then log that we are here.
# If s2disk worked, this should happen after power is back and we resume.
sleep $FINALDELAY
logger -s -t upsevent -i -p daemon.info "back from s2disk"

;;

# ----------------------------------------------------------------------
*)
logger -s -t upsevent -i -p daemon.err "Unrecognized UPS event: $EVENT"
;;

# ----------------------------------------------------------------------
esac
