#!/bin/bash

(
/usr/libexec/chrony-graph/graph-header all-offset.png "%1.0f us" "all clocks (offset)" ""
/usr/libexec/chrony-graph/foreach-stat "'__FILE__' using 1:(\$4*1000000) title '__TITLE__' with line \\"
echo 
) | gnuplot

if [ -f "${TITLES}" ]; then
  titles=$(cat "${TITLES}")
else
  titles=$(
    for stat in statistics.*; do
      echo $stat ${stat#statistics.}
    done
  )
fi

#(
#  /usr/libexec/chrony-graph/graph-header remote-strat1.png "%1.0f us" "offset of remote strat1s" ""
#  i=0
#  echo "$titles" | while read file title; do
#    if [ $i != 0 ]; then
#      echo -n ,
#    else
#      i=1
#    fi
#    echo "'$file' using 1:(\$4*1000000) title '$title' with line \\"
#  done
#) | gnuplot
#
#(
#  /usr/libexec/chrony-graph/graph-header remote-strat1-downstream.png "%1.0f us" "offset-rtt/2 of remote strat1s" ""
#  i=0
#  echo "$titles" | while read file title; do
#    measurements_file=`echo $file | sed 's/^statistics/measurements/'`
#    if [ -f $measurements_file ]; then
#      if [ $i != 0 ]; then
#        echo -n ,
#      else
#        i=1
#      fi
#      echo "'$measurements_file' using 1:((\$11-\$12/2)*1000000) title '$title' with line \\"
#    fi
#  done
#  echo
#) | gnuplot

echo "$titles" | while read file title; do
  imagename=`echo $file | sed 's/:/_/g'`
  measurements_file=`echo $file | sed 's/^statistics/measurements/'`
  (
    if [ -f $measurements_file ]; then
      FIFTY=`/usr/libexec/chrony-graph/percentile 10 50 $measurements_file | /usr/libexec/chrony-graph/mul 1000000`
      CUSTOM="set label 1 gprintf('50%% = $FIFTY us',50) at graph 0.01,0.05 left front"
      /usr/libexec/chrony-graph/graph-header remote-${imagename}.png "%1.0f us" "offset of $title" "$CUSTOM"
      echo "'$measurements_file' using 1:(\$11*1000000) title 'offset' with line, \\"
      echo "'$measurements_file' using 1:((\$11+\$12/2)*1000000) title 'offset+rtt/2' with line, \\"
      echo "'$measurements_file' using 1:((\$11-\$12/2)*1000000) title 'offset-rtt/2' with line, \\"
      echo "$FIFTY title '50th percentile'"
    else
      FIFTY=`/usr/libexec/chrony-graph/percentile 3 50 $file | /usr/libexec/chrony-graph/mul 1000000`
      CUSTOM="set label 1 gprintf('50%% = $FIFTY us',50) at graph 0.01,0.05 left front"
      /usr/libexec/chrony-graph/graph-header remote-${imagename}.png "%1.0f us" "offset of $title" "$CUSTOM"
      echo "'$file' using 1:(\$4*1000000) title 'offset' with line, \\"
      echo "$FIFTY title '50th percentile'"
    fi
  ) | gnuplot
done
