#!/bin/sh
# @uptime - how long the xmppcb bot has been running
#
# The bot exec's this script directly, so its parent process ($PPID) is
# the xmppcb process itself; ps tells us how long that process has run.

secs=$(ps -o etimes= -p "$PPID" 2>/dev/null | tr -cd '0-9')

if [ -n "$secs" ]; then
	d=$(( secs / 86400 ))
	h=$(( secs % 86400 / 3600 ))
	m=$(( secs % 3600 / 60 ))
	s=$(( secs % 60 ))
	if   [ "$d" -gt 0 ]; then up="${d}d ${h}h ${m}m ${s}s"
	elif [ "$h" -gt 0 ]; then up="${h}h ${m}m ${s}s"
	elif [ "$m" -gt 0 ]; then up="${m}m ${s}s"
	else                      up="${s}s"
	fi
	echo "xmppcb up: $up"
else
	# fallback for a ps without 'etimes': raw elapsed string [dd-]hh:mm:ss
	et=$(ps -o etime= -p "$PPID" 2>/dev/null | tr -d ' ')
	if [ -n "$et" ]; then
		echo "xmppcb up: $et"
	else
		echo "uptime: cannot read bot process (pid $PPID)"
		exit 1
	fi
fi
