#!/bin/bash

declare -i LOGDAYS=7
if [ -x startime ]; then
  STARTIME=`./startime`
else
  NOW=`date +%s`
  STARTIME=`expr $NOW - $(( 60 * 60 * 24 * ${LOGDAYS} ))`
fi

if [ -n "$CHRONY_LOGDIR" ]; then
  LOGDIR=$CHRONY_LOGDIR
else
  LOGDIR=/var/log/chrony
fi

if [ -x /usr/libexec/chrony-graph/copy-logfiles ]; then
  test -d log-chrony || mkdir log-chrony
  test -d log || mkdir log
  /usr/libexec/chrony-graph/copy-logfiles
  LOGDIR=log-chrony
fi

function limit_time {
  awk '{if($1 > '$STARTIME') { print }}'
}

function cat_logfiles {
  file_pattern="$1"

  find $LOGDIR -name "$file_pattern" \! -name \*.?z -mtime -$LOGDAYS -exec cat '{}' +
  find $LOGDIR -name "$file_pattern".xz -mtime -$LOGDAYS -exec xzcat '{}' +
}

rm -f statistics*
# split the statistics logs based on the source IP
cat_logfiles statistics.log\* | /usr/libexec/chrony-graph/timestamps | limit_time | sort -n | /usr/libexec/chrony-graph/split statistics ~/.chrony-graph.aliases.conf

rm -f measurements.*
# measurements logs - also split based on source IP
cat_logfiles measurements.log\* | /usr/libexec/chrony-graph/timestamps | limit_time | sort -n | /usr/libexec/chrony-graph/split measurements ~/.chrony-graph.aliases.conf

# local clock info goes in one logfile
cat_logfiles tracking.log\* | /usr/libexec/chrony-graph/timestamps | limit_time | sort -n >tracking.log


# optional GPS log processing
if [ -f log/gps-lock ]; then
  sed 's/ \([0-9]\+:[0-9]\+\) / \1:00 /' <log/gps-lock | /usr/libexec/chrony-graph/timestamps | limit_time >gps-lock
fi
if [ -f log/snr-history ]; then
  sed 's/ \([0-9]\+:[0-9]\+\) / \1:00 /' <log/snr-history | /usr/libexec/chrony-graph/timestamps | limit_time >snr-history
fi

if [ -f log/gps-lock2 ]; then
  sed 's/ \([0-9]\+:[0-9]\+\) / \1:00 /' <log/gps-lock2 | /usr/libexec/chrony-graph/timestamps | limit_time >gps-lock2
fi
if [ -f log/snr-history2 ]; then
  sed 's/ \([0-9]\+:[0-9]\+\) / \1:00 /' <log/snr-history2 | /usr/libexec/chrony-graph/timestamps | limit_time >snr-history2
fi

/usr/libexec/chrony-graph/index >index.html

/usr/libexec/chrony-graph/plot

> .tmp
for i in `ls -1d remote-statistics.*.png | sort -V`
do
   SERVER_NAME="${i%.png}"
   SERVER_NAME="${SERVER_NAME#remote-statistics.}"
   echo "<img src=\"${i}\" alt='Remote Clock: ${SERVER_NAME}'><br>" >> .tmp
done
sed -i '
/remote-statistics.SET_IP_HERE.png/{
s@^.*@@
r .tmp
}' index.html

rm .tmp

/usr/libexec/chrony-graph/copy-to-website
