#!/bin/bash
#
# Returns a path where a log file will be archived. This script is called
# once for each log file being archived. Usage is:
#
# make-archive-name <origname> <writer> <timestamp-when-opened> [<timestamp-when-closed>]
#
# Example:
# make-archive-name conn.log ascii 2015-01-20-15-48-23 2015-01-20-16-00-00
#
# Example output:
# 2015-01-20/conn.15:48:23-16:00:00.log
#
#   origname: The original name of the log file being archived (e.g. conn.log).
#   writer:   The name of the log writer type that produced the file.
#   timestamp-when-opened: The timestamp when the log file being archived was
#                          created.
#   timestamp-when-closed: The timestamp when the log file being archived was
#                          finished.  Optional.  If not given, the path is used
#                          by another script to create a link to the current
#                          live version of the file.
#
# Additionally, the following environment variables are passed:
#
#  ZEEK_ARG_LOG_SUFFIX: A suffix to append to the final archive name to avoid
#                       filename clashes when running with multiple loggers.
#                       This is populated with the name of the logger node,
#                       e.g. logger-1, as specified in cluster-layout.zeek
#                       only when multiple loggers are configured in node.cfg.
#
# The writer is derived from the WRITER_* constants and lower-cased; e.g.,
# "ascii" for Log::WRITER_ASCII.
#
# Times are given in the form "year-month-day-hour-minute-second",
# e.g., "2010-03-30-13-12-04"
#
# The script must return the path under which the file should be
# archived.  A relative path will be interpreted as
# relative to ZeekControl's standard log directory.
#
# Note that even if the logs will later be compressed, this script should
# always return the filename without any compression extension (such as ".gz");
# that extension will be appended later.

ext=`echo $1 | sed 's/^.*\.//'`
name=`basename $1 .$ext`
writer=$2
opened=$3
closed=$4

day=`echo $opened  | awk -F - '{printf "%s-%s-%s", $1, $2, $3}'`
from=`echo $opened | awk -F - '{printf "%s:%s:%s", $4, $5, $6}'`
to=`echo $closed | awk -F - '{printf "%s:%s:%s", $4, $5, $6}'`

suffix=""
if [ -n "${ZEEK_ARG_LOG_SUFFIX}" ]; then
    suffix="-${ZEEK_ARG_LOG_SUFFIX}"
fi

if [ -n "$closed" ]; then
   echo $day/$name.$from-$to$suffix.$ext
else
   echo $day/$name.$from-current$suffix.$ext
fi

