#!/bin/bash
#
# functions
#

# width:

STAT_COL=$(stty size)
# strip the rows number, we just want columns
STAT_COL=${STAT_COL##* }
if [ "$STAT_COL" = "0" ]; then
	# if output was 0 (serial console), set default width to 80
	STAT_COL=80
elif [ ! -t 1 ]; then
	# disable color on output to non-tty
	STAT_COL=80
	USECOLOR=""
fi
# we use 13 characters for our own stuff
STAT_COL=$[$STAT_COL - 13]

# disable colors on broken terminals
TERM_COLORS="$(tput colors 2>/dev/null)"
if [ -n "${TERM_COLORS}" ]; then
	case "${TERM_COLORS}" in
		*[!0-9]*)
			USECOLOR=""
			;;
		*)
			[ "${TERM_COLORS}" -lt 8 ] && USECOLOR=""
			;;
	esac
else
	USECOLOR=""
fi
unset TERM_COLORS

# colors:
if [ "$USECOLOR" = "YES" -o "$USECOLOR" = "yes" ]; then
	C_MAIN="\033[1;37m"       # main text
	C_OTHER="\033[1;34m"      # prefix & brackets
	C_SEPARATOR="\033[1;30m"  # separator
	
	C_BUSY="\033[0;36m"		# busy
	C_FAIL="\033[1;31m"		# failed
	C_DONE="\033[1;37m"		# completed
	C_BKGD="\033[1;35m"		# backgrounded
	
	C_H1="\033[1;37m"		# highlight text 1
	C_H2="\033[1;36m"		# highlight text 2
	
	C_CLEAR="\033[1;0m"
fi

if [ -t 1 ]; then
	SAVE_POSITION="\033[s"
	RESTORE_POSITION="\033[u"
	DEL_TEXT="\033[$(($STAT_COL+4))G"
fi

# prefixes:

PREFIX_REG="::"
PREFIX_HL=" >"

# functions:

deltext() {
	echo -ne "$DEL_TEXT"
}

printhl() {
	echo -e "$C_OTHER$PREFIX_HL $C_H1$1$C_CLEAR "
}

printsep() {
	echo -e "\n$C_SEPARATOR   ------------------------------\n"
}

stat_bkgd() {
	echo -ne "$C_OTHER$PREFIX_REG $C_MAIN$1$C_CLEAR "
	deltext
	echo -ne "   $C_OTHER[${C_BKGD}BKGD$C_OTHER]$C_CLEAR "
}

stat_busy() {
	echo -ne "$C_OTHER$PREFIX_REG $C_MAIN$1$C_CLEAR "
	echo -ne "${SAVE_POSITION}"
	deltext
	echo -ne "   $C_OTHER[${C_BUSY}BUSY$C_OTHER]$C_CLEAR "
}

stat_append() {
	echo -ne "${RESTORE_POSITION}"
	echo -ne "$C_MAIN$1$C_CLEAR"
	echo -ne "${SAVE_POSITION}"
}

stat_done() {
	deltext
	echo -e "   $C_OTHER[${C_DONE}DONE$C_OTHER]$C_CLEAR "
}

stat_fail() {
	deltext
	echo -e "   $C_OTHER[${C_FAIL}FAIL$C_OTHER]$C_CLEAR "
}

stat_die() {
	retval=1
	[ "$1" = "" ] || retval=$1
	stat_fail
	exit $retval
}

status() {
	stat_busy "$1"
	shift
	$* >/dev/null 2>&1
	if [ $? -eq 0 ]; then
		stat_done
		return 0
	else
		stat_fail
		return 1
	fi
}

# daemons:

add_daemon() {
	[ -d /var/run/daemons ] || mkdir -p /var/run/daemons
	touch /var/run/daemons/$1
}

rm_daemon() {
	rm -f /var/run/daemons/$1
}

ck_daemon() {
	[ -f /var/run/daemons/$1 ] && return 1
	return 0
}

# End of file
# vim: set ts=2 noet:
