#!/bin/sh
#
#    byobu-statusd: byobu's status gathering daemon
#
#    Copyright (C) 2011 Dustin Kirkland
#
#    Authors: Dustin Kirkland <kirkland@ubuntu.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, version 3 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

PKG="byobu"
[ -z "${BYOBU_PREFIX}" ] && export BYOBU_PREFIX="/usr" || export BYOBU_PREFIX
. "${BYOBU_PREFIX}/lib/${PKG}/.common"

# Clean and create cache directories
rm -rf "$BYOBU_RUN_DIR/status" "$BYOBU_RUN_DIR/.last"
mkdir -p "$BYOBU_RUN_DIR/status" "$BYOBU_RUN_DIR/.last"

# Source configurations
for i in "${BYOBU_PREFIX}/share/$PKG/status/status" "${BYOBU_PREFIX}/share/$PKG/status/statusrc" "$BYOBU_CONFIG_DIR/status" "$BYOBU_CONFIG_DIR/statusrc" "$BYOBU_CONFIG_DIR/color"; do
	[ -r "$i" ] && . "$i"
done

# Run each status function as necessary
while true; do
	# Make sure status is not disabled
	if [ -f "$BYOBU_CONFIG_DIR/status.disable" ]; then
		rm -f "$BYOBU_RUN_DIR/status"/* "$BYOBU_RUN_DIR/.last"/*
		exit 0
	fi
	get_now; now=${_RET}
	# Re-source configuration, if changed since last run
	for i in "${BYOBU_PREFIX}/share/$PKG/status/status" "${BYOBU_PREFIX}/share/$PKG/status/statusrc" "$BYOBU_CONFIG_DIR/status" "$BYOBU_CONFIG_DIR/statusrc"; do
		[ -r "$i" ] && [ "$i" -nt "$BYOBU_RUN_DIR/status" ] && . "$i"
	done
	for i in "$BYOBU_PREFIX/lib/$PKG/"*; do
		case "$i" in
			*/time_binary|*/Makefile.am) continue ;;
		esac
		i=${i##*/}
		cachepath="$BYOBU_RUN_DIR/status/$i"
		lastpath="$BYOBU_RUN_DIR/.last/$i"
		# Check if this status is enabled
		eval x="\$$i"
		if [ "$x" != "1" ]; then
			# This item is disabled; clean up and continue
			rm -f "$cachepath" "$lastpath"
			continue
		fi
		[ -r "$lastpath" ] && read lastrun < "$lastpath" || lastrun=0
		status_freq "$i"
		expiry=$(($lastrun+$_RET))
		find_script "$i" && path="$_RET" || path=/dev/null
		# Re-source status function, if changed since last run
		if [ "$path" -nt "$lastpath" ] || [ ! -e "$lastpath" ]; then
			. "$path"
			lastrun=0
		fi
		# Update cache now, if necessary
		if [ $now -ge $expiry ] || [ "$lastrun" = "0" ]; then
			"__$i" > "$cachepath"
			echo "$now" > "$lastpath"
		fi
	done
	sleep 2
done
exit 0
