#!/bin/bash

#
# Copyright 2015-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# -----------------------------------------------------------------------------
# Tool to stitch together ONOS logs collected via onos-diagniostics tool.
# -----------------------------------------------------------------------------
function usage {
    echo "usage: onos-log-query [-n query-name] [-f from-time] [-t to-time] [-x] [node]" >&2
    exit 1
}

name=query  # default name
onlyts=0

while getopts n:f:t:x?h o; do
    case "$o" in
        x) onlyts=1;;
        n) name="$OPTARG";;
        f) from="$OPTARG";;
        t) to="$OPTARG";;
        *) usage;;
    esac
done

let OPC=$OPTIND-1
shift $OPC

[ "$name" = "karaf" ] && echo "Name cannot be 'karaf'!" && usage

function stitchLogs {
    awk -v onlyts=${onlyts} -v from="${from}" -v to="${to}" '
        BEGIN { on = !onlyts && from == "" && to == ""; FS="|"; }
        /^[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}/ {
            on = (from == "" || $1 >= from) && (to == "" || $1 <= to);
            if (on) { print $0; }
            next;
        }
        { if (on && !onlyts) { print $0; }}
    ' $(ls -r1 karaf.log*) > ${name}.log
}

function stitchNodeLogs {
    pushd $1 &>/dev/null
    stitchLogs
    popd &>/dev/null
    echo ${1}/${name}.log
}

if [ $# -eq 1 -a -d "$1" ]; then
    stitchNodeLogs $1
elif [ $# -ge 1 ]; then
    echo "No node directory for '$1'!" >&2
    usage
elif ls karaf.log &>/dev/null; then
    stitchLogs
elif ls */karaf.log &>/dev/null; then
    for node in $(ls */karaf.log | cut -d/ -f1); do
        stitchNodeLogs $node &
    done
    wait
    awk '{ print FILENAME " | " $0; }' */${name}.log | \
        sed "s:/${name}.log::" | \
        egrep '[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3}' | \
        sort -t\| -k2,2 > ${name}.log
    echo ${name}.log
fi
