#!/bin/sh

# alog script for venusd exec - displays log file
# Copyright (c) 2016 Wavestore Global Ltd

# usage: alog [-options] <logname>
# options:
# -a outputs all, otherwise only last 1000 lines output
# -d outputs debug(network traffic) otherwise just interpretation and messages
# -f outputs a single file
# -ad all+debug
# -afd all onefile including debug

N1="$1"
A=""
D=""
F=""
if [ "${N1:0:1}" == "-" ]; then
        O="$1"
        N1="$2"
        A="${O/*a*/-a}"
        D="${O/*d*/-d}"
        F="${O/*f*/-f}"
fi

NN="/home/dvr/log/$N1"
N="$NN"
if [ "$F" == "-f" ]; then
	# if one file, just use this
	N="$NN"
else
	# otherwise add all files together
	N="$NN"
	[ -f "${NN}.1" ] && N="${NN}.1 $N"
	[ -f "${NN}.2" ] && N="${NN}.2 $N"
fi

if [ "$N1" -a -f "$NN" ]; then
        if [ "$D" == "-d" ]; then
		# with debug, show every line
                if [ "$A" == "-a" ]; then
                        cat $N
                else
                        tail -n1000 $N
                fi
        else
		# no debug
                if [ "$A" == "-a" ]; then
                        cat $N | grep -v " [<>] "
                else
                        cat $N | grep -v " [<>] " | tail -n1000
                fi
        fi
elif [ "$N1" ]; then
        echo "Log file '$N1' does not exist"
else
        echo "usage: alog [-options] <logname>"
        echo "options: -a all; -d debug(<,> lines); -f onefile; -ad all+debug"
	echo "if -a not specified, only the last 1000 lines are output"
	echo "<logname> may be one of:"
	cd /home/dvr/log
	if [ "$F" == "-f" ]; then
		# onefile mode: list all files including .1 .2 extensions
		ls -1
	else
		# list all files excluding extensions
		ls -1 | grep -v ".[12]$"
	fi
fi
