#!/bin/sh -e

# Subtract 3 hours for all log files and put to a separate log
# adj.sh -$((3 * 3600)) *.log > new/sum.log
# 
# Add 100 seconds to lab-2015-02-25.log
# adj.sh 100 *.log lab-2015-02-25.log

error() {
    echo "$(basename $0): error: $@"
    exit 1
}

test "$1" || error "provide adjust value (seconds)"
ADJ="$1"
shift

test ${#@} -ne 0 || error "provide log file" 

awk '
BEGIN { OFS = "  " }

{
    # Convert ISO 8601 date and time of day format to seconds
    # since 1970-01-01 00:00:00 UTC.
    cmd = "date -d " $1 " +%s"
    cmd | getline date
    close(cmd)

    # Adjust time.
    date += '"$ADJ"'

    # Convert date back to ISO 8601 format.
    cmd = "date -d @" date " +%FT%T"
    cmd | getline date
    close(cmd)

    day = date
    sub(/T.*/, "", day)

    # Detect a new day. 
    if (last_day != day) {
        if (last_day) print "#end"
        print "#begin lab-" day ".log" 
    }

    # Print a line with adjusted time.
    sub(/^[^ ][^ ]*[ ][ ]*/, "")
    print date, $0

    last_day = day
}

END { if (last_day) print "#end" }' "$@"

