#!/usr/bin/env bash
# lastwake -- show time since system resumed from sleep
#
# Similar to `uptime` but returns only the duration of the current session.

. lib.bash || exit

usage() {
	echo "Usage: $progname [-q]"
	echo ""
	echo_opt "-q"		"print only the timestamp"
}

opt_quiet=0

while getopts :q OPT; do
	case $OPT in
	q) opt_quiet=1;;
	*) lib:die_getopts;;
	esac
done; shift $[OPTIND-1]

if (( $# )); then
	vdie "excess arguments"
fi

x=$(journalctl -b -o json -n 1 MESSAGE_ID=8811e6df2a8e40f58a94cea26f8ebf14)

if [[ $x ]]; then
	ts=$(jq -r .__REALTIME_TIMESTAMP <<< "$x")
	ts=$[ts/1000000]
	if (( !opt_quiet )); then
		abstime=$(date -d @$ts +%T)
		reltime=$(interval $[`date +%s` - ts])
		echo "System resumed from sleep $reltime ago ($abstime)"
	else
		echo "$ts"
	fi
else
	if (( !opt_quiet )); then
		echo "System did not sleep since last boot."
	fi
	exit 1
fi
