#!/bin/bash
#
# ::copy::
#
# reformat samba logs for human reading
#
CMD=$(basename "$0")
CMDVER="1.5"
CMDSTR="$CMD v$CMDVER (2023-10-30)"

set -e -u

usage()
{
	echo "
usage: $CMD [--nosort] [--nomore] samba_log_file(s)...

options:
  --nosort	do not sort logfiles (see below)
  --nomore	do not pipe files to 'more' program

file order
----------
  when multiple files are listed, they are sorted in time-reverse
  order and concatenated; this produces a coherent log entries
  timeline, but only if the logs are referred to the same client
  (typically \"log.clientname\" and \"log.clientname.old\")

  with --nosort option the files are processed one by one, in the
  same order you listed on commandline
" >&2
	exit 127
}

filter_lines()
{
	local line=
	local buf=
	local sq="["

	while :
	do
		read line || break
		case $line in
		  \[*)	buf=${line/.*/}; buf=${buf/$sq/}; continue ;;
		  *)	echo "$buf $line"; buf= ;;
		esac
	done
	return 0
}



# (MAIN)

nosort=false
more="more"

[ "X${1:-}" = "X--nosort" ] && { nosort=true; shift; }
[ "X${1:-}" = "X--nomore" ] && { more="cat"; shift; }
[ $# = 0 ] && usage

if $nosort
then
	echo -e "\n== $CMDSTR ==\n"
	for file
	do
		echo -e "\n== file: $file\n"
		filter_lines <"$file"
	done
else
	files=$(ls -tr "$@")
	echo -e "\n== $CMDSTR == samba logs:" $files "==\n"
	cat $files | filter_lines
fi | $more

exit 0
