#!/bin/sh
path="${0%/*}"
. "$path/inc.sh"

usage () {
	die 'gwmodem stat [-c|--count [VALUE]] [-r|--raw] -- [FILES]'
}

logCount=2
db=9
db1=
db2=
db3=
human=0
raw=false
noformat=false
utc=true
skip=0
while : ; do
	case "$1" in
		-c|--c|--count)
			case "$#" in 1) usage ;; esac; shift
			logCount="$1"
		;;
		-c=*|--c=*|--count=*)
			logCount="$(expr "$1" : '-[^=]*=\(.*\)')"
		;;
		-d|--d|--db)
			case "$#" in 1) usage ;; esac; shift
			db="$1"
		;;
		-d=*|--d=*|--db=*)
			db="$(expr "$1" : '-[^=]*=\(.*\)')"
		;;
		--db1=*)
			db1="$(expr "$1" : '-[^=]*=\(.*\)')"
		;;
		--db2=*)
			db2="$(expr "$1" : '-[^=]*=\(.*\)')"
		;;
		--db3=*)
			db3="$(expr "$1" : '-[^=]*=\(.*\)')"
		;;
		-h|--h|--human)
			human=h
		;;
		-l|--l|--local)
			utc=false
		;;
		-n|--n|--no-format)
			noformat=true
		;;
		-r|--r|--raw)
			raw=true
		;;
		-s|--s|--skip)
			skip=1
		;;
		-u|--u|--utc)
			utc=true
		;;
		--)
			shift
			break
		;;
		-*)
			usage
		;;
		*)
			break
		;;
	esac
	shift
done

LOG='/var/log/telem/modem_st.csv'
fnames="${@:-$(ls -1 ${LOG}* | sort -r | tail -n ${logCount})}"

if $raw; then
	# Print as is
	cat "${LOG}.1" "${LOG}.0" "${LOG}" 2>/dev/null
else
	if $utc; then
		tzs=0
	else
		# If dates are from multiple timezones (summer/winter), then this will not work
		tz="$(date +%z)"
		tzs="$(echo "${tz:0:1}1 ${tz:1:2} ${tz:3:2}" | awk '{print $1*(($2*3600)+($3*60))}')"
	fi
	tmpfile="$(mktemp -t gwmodem-stat-tmp.XXXXXX)"
	xzcat -f ${fnames} 2>/dev/null | strings \
	| $path/modem_st.csv.s.awk  -vqdb=${db1:-$db} -vedb=${db2:-$db} -vndb=${db3:-300} -vdur=${human} -vtz=${tzs} -vskip=${skip} > "${tmpfile}"
	if $noformat; then
		# Print without formating
		cat "${tmpfile}"
	else
		# Print formated
		(
			$path/modem_st.csv.f.awk -vlen=1 "${tmpfile}"
			cat "${tmpfile}"
		) \
		| $path/modem_st.csv.f.awk -vfmt=1
	fi
	rm "${tmpfile}"
fi
