#!/usr/local/bin/cbsd
#v10.1.0
MYARG=""
MYOPTARG="shownode display node header mode"
MYDESC="Show BSD kernels"
CBSDMODULE="sys"
ADDHELP="shownode=1 - show nodename for jails\n\
node= only for current node\n\
header=0 don't print header\n\
display= list by comma for column. Default: platform,name,arch,targetarch,ver,stable,elf,status,date\n\
  additional: source\n"

. ${subrdir}/nc.subr
. ${system}
. ${strings}
. ${tools}

. ${cbsdinit}

[ -z "${display}" ] && display="platform,name,arch,targetarch,ver,stable,elf,status,date"

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

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

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

# if $1 = "Unregister" then overwrite status to "Unregister"
populate_output_data()
{
	local _i _val src_size

	_status=

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


}


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

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

	_sql="SELECT platform,name,arch,targetarch,ver,stable,elf,status,date,source FROM bsdkernel"

	OIFS="${IFS}"
	IFS="|"
	sqldelimer="|"

	cbsdsqlro ${sqlfile} ${_sql} | while read platform name arch targetarch ver stable elf status date source; do
		IFS="${OIFS}"
		populate_output_data
		printf "${N2_COLOR}"
		printf "${_status}"
		printf "${N0_COLOR}\n"
		IFS="|"
	done
	IFS="${OIFS}"
}

show_remote()
{
	show_header

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

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

show_local()
{
	local _errcode _status

	show_header
	show_kernelsdata_from_sql local
}

show_kernels()
{
	if [ -n "${node}" ]; then
		show_remote
		exit
	fi

	show_local
}

#### MAIN
[ -z "${header}" ] && header=1
show_kernels | ${COLUMN_CMD} -t

exit 0
