#!/bin/sh

# Merge a set of syslog files.  The syslogs are turned into siptraces,
# which are then fed to siptrace-merge to be combined into one siptrace
# file, named merged.xml.
# Most options are passed to siptrace-merge, so all of the siptrace-merge
# options can be used.  The exceptions are --after=xxx and --before=xxx,
# which are passed to syslog2siptrace (which are the only such options
# that it accepts).  This is done because applying --before/--after at
# the syslog2siptrace stage is much faster when the logs are large.

# Failed subcommands will cause this script to exit.
set -e

# Separate the options from the files.
SYSLOG2SIPTRACE_OPTIONS=
SIPTRACE_MERGE_OPTIONS=
XML_PREFIX=
OUTPUT=merged.xml
while [[ "$1" = -* && "$1" != -- ]]
do
  if [[ "$1" = --after=* ]] || [[ "$1" = --before=* ]]
  then
    # The --before and --after options are passed to syslog2siptrace
    # rather than siptrace-merge to speed up processing.
    SYSLOG2SIPTRACE_OPTIONS="$SYSLOG2SIPTRACE_OPTIONS $1"
  elif [[ "$1" = --xml=* ]]
  then
    # The --xml option is a prefix (directory, usually) into which
    # the generated XML files are to be placed.
    XML_PREFIX="${1#--xml=}"
  elif [[ "$1" = --output=* ]]
  then
    # The --output option specifies the output file.
    OUTPUT="${1#--output=}"
  else
    SIPTRACE_MERGE_OPTIONS="$SIPTRACE_MERGE_OPTIONS $1"
  fi
  shift
done
if [[ "$1" = -- ]]
then
  shift
fi

# The list of XML files to merge.
XML=
for LOG in ${@:-sip*.log}
do
  F="${XML_PREFIX}${LOG%.log}.xml"
  syslog2siptrace $SYSLOG2SIPTRACE_OPTIONS <$LOG >$F
  XML="$XML $F"
done

siptrace-merge $SIPTRACE_MERGE_OPTIONS -- $XML >$OUTPUT
