#!/usr/local/bin/cbsd
#v10.1.6
MYARG=""
MYOPTARG="header"
MYDESC="List of task queue and status"
CBSDMODULE="taskd"
EXTHELP="wf_taskd"

. ${subrdir}/nc.subr

. ${cbsdinit}

. ${system}


[ -z "${display}" ] && display="id,status,owner,cmd,logfile,errcode"
#[ "${shownode}" = "1" ] && display="nodename,${display}"

#remove commas for loop action on header
mydisplay=$( echo ${display} | ${TR_CMD} ',' '|' )

# upper for header
myheader=$( echo ${mydisplay} | ${TR_CMD} '[:lower:]' '[:upper:]' )

conv_status()
{
	case "${status}" in
		0)
			status="Pending"
			;;
		1)
			status="In Progress"
			;;
		2)
			status="Complete"
			;;
		*)
			status="Unknown"
			;;
	esac
}


show_header()
{
	local _header="${H1_COLOR}${BOLD}${myheader}${N0_COLOR}"
	[ ${header} -ne 0 ] && ${ECHO} ${_header}
}

populate_output_data()
{
	_status=
	local IFS="|"

	# populate values for in output string
	for _i in ${mydisplay}; do
		_val=""
		IFS="|"
		eval _val="\$$_i"
		IFS=" "
		if [ -z "${_status}" ]; then
			_status="${N0_COLOR}${_val}"
		else
			_status="${_status}|${_val}"
		fi
		IFS="|"
	done
}

# $1 - which file from. Eg: local
show_jaildata_from_sql()
{
	local _i IFS

	#   set sqlfile for ". rcconf" including
	if [ -n "${1}" ]; then
		sqlfile="$1"
	else
		sqlfile="cbsdtaskd"
	fi

	IFS="|"

	cbsdsqlro ${sqlfile} SELECT id,status,owner,cmd,logfile,errcode,jname FROM taskd | while read id status owner cmd logfile errcode jname; do
		conv_status
		populate_output_data
		printf "${N2_COLOR}"
		printf "${_status}"
		printf "${N0_COLOR}\n"
	done
	IFS=" "
}

show_remote()
{

	show_header

	[ -z "${node}" ] && node=$(cbsd node mode=list header=0 allinfo=0)

	for _n in $node; do
		nodename="${_n}"
		show_jaildata_from_sql "inv.${_n}"
	done
}

show_local()
{
	local _errcode _status

	[ ${header} -eq 1 ] && show_header

	show_jaildata_from_sql cbsdtaskd
}

show_tasks()
{

	if [ -n "${node}" ]; then
		show_remote
		exit 0
	fi

	if [ -n "${alljails}" ]; then
		show_local
		header=0
		show_remote
	else
		show_local
	fi

}

## MAIN
[ -z "${header}" ] && header=1
#sqldelimer=" "

show_tasks | ${COLUMN_CMD} -s "|" -t

exit 0
