#!/bin/sh
SCRIPT="${0}"

die() {
	echo >&2 "$@"
	exit 1
}

usage() {
	die 'gwpipelog [OPTIONS] -- file'
}

ROTATE=true
RCOUNT=5
RSIZE=500k
ADDTIME=false
TZV="$TZ"
while : ; do
	case "$1" in
		-c|--c|--count) # H: rotated file count
			ROTATE=true
			case "$#" in 1) usage ;; esac; shift
			RCOUNT="$1"
		;;
		-c=*|--c=*|--count=*)
			ROTATE=true
			RCOUNT="$(expr "$1" : '-[^=]*=\(.*\)')"
		;;
		-s|--s|--size)  # H: rotated file size
			ROTATE=true
			case "$#" in 1) usage ;; esac; shift
			RSIZE="$1"
		;;
		-s=*|--s=*|--size=*)
			ROTATE=true
			RSIZE="$(expr "$1" : '-[^=]*=\(.*\)')"
		;;
		-t|--t|--time)  # H: prepend time
			ADDTIME=true
		;;
		-u|--u|--utc)   # H: prepend UTC time
			ADDTIME=true
			TZV=UTC0
		;;
		--)
			shift
			break
		;;
		-*)
			usage
		;;
		*)
			break
		;;
	esac
	shift
done

FNAME="$1"
shift

[ -z "${FNAME}" ] && usage

trap exit_trap INT EXIT PIPE TERM

function exit_trap() {
	pkill -P "$$"
}

rotatelog() {
	logfile="$1"
	# Delete older than 8 days
	#find "${logfile}"* -type f -mtime +8 -delete 2>/dev/null
	# Keep only max N latest files
	ls -1tp "${logfile}"* 2>/dev/null | tail -n +${RCOUNT} | xargs -d '\n' -r rm --
	# Rotate logs
	STAMP="$(date +%j%H%M)" # WEEK-HOUR-MINUTE
	find "${logfile}" -type f -size +${RSIZE} \
	-exec sh -c 'mv "$0" "$0.$1"' {} "${STAMP}" \; 2>/dev/null
}

if ${ROTATE}; then
	while :; do
		rotatelog "${FNAME}"
		# Every 6 minutes
		sleep 361
	done &
fi

if ${ADDTIME}; then
	TZ="$TZV" awk -v f="${FNAME}" '{print strftime("%FT%H:%M:%SZ")" "$0 >> f; if(n++>10){n=0;close(f)}}'
else
	awk -v f="${FNAME}" '{print >> f; if(n++>10){n=0;close(f)}}'
fi
