#!/usr/bin/env bash
# lastdown -- show the last time the system was turned off

. 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

text=""
if [[ ! $text ]]; then
	x=$(journalctl -b -o json -n 1 MESSAGE_ID=6bbd95ee977941e497c48be27c254128)
	if [[ $x ]]; then
		text="went to sleep"
	fi
fi
if [[ ! $text ]]; then
	x=$(journalctl -b -1 -o json -n 1)
	text="was unexpectedly powered off"
fi

if [[ $x ]]; then
	ts=$(jq -r .__REALTIME_TIMESTAMP <<< "$x")
	ts=$[ts/1000000]
	if (( !opt_quiet )); then
		abstime=$(date -d @$ts +"%F %T")
		reltime=$(interval $[`date +%s` - ts])
		echo "System $text $reltime ago ($abstime)"
	else
		echo "$ts"
	fi
else
	xxxxx
fi
