#!/bin/bash
# This script will let you filter  a queue log file by start and end dates with an option filter string
#
# Example: ./filter_queuelog 2018-01-01 2018-01-31 /var/log/asterisk/queue_log
#
# It will print out only queue_log lines for juanuay 2018
#
#
# ./filter_queuelog 2018-03-03 2018-03-10 /var/log/asterisk/queue_log John
#
# It will print out queue_log lines for march 3 to 10 containing John
#

me=`basename "$0"`

if [[ $# -lt 3 ]] ; then
    echo "Usage: ./$me [START-DATE] [END-DATE] /var/log/asterisk/queue_log [FILTERSTRING] [--human]"
    exit 0
fi

INITIAL_TIMESTAMP=$(date -d "$1 00:00:00" +%s)
FINAL_TIMESTAMP=$(date -d "$2 23:59:59" +%s)

FILE="$3"
FILTER="$4"
HUMAN=0

# detectar flag
if [[ "$4" == "--human" ]]; then
    HUMAN=1
    FILTER=""
elif [[ "$5" == "--human" ]]; then
    HUMAN=1
fi

if [ ! -f "$FILE" ]; then
   echo "File $FILE not found!"
   exit 0
fi

awk -F'|' -v start="$INITIAL_TIMESTAMP" -v end="$FINAL_TIMESTAMP" -v filter="$FILTER" -v human="$HUMAN" '
{
    if ($1 >= start && $1 <= end) {

        if (filter == "" || $0 ~ filter) {

            if (human) {
                d = strftime("%Y-%m-%d %H:%M:%S", $1)
                print d " " $0
            } else {
                print $0
            }

        }

    }
}
' "$FILE"
