#!/bin/bash
#
# test_chrony
#
# check chrony status
#
#############################################
#
unset full
while getopts f op; do
  case "$op" in
    f) full=1;;
    *) echo "usage: $(basename $0) [-f]";;
  esac
done
shift $(( $OPTIND -1))
#
. `dirname $0`/uls_header
#
export PATH=/usr/sbin:$PATH
#
if systemctl status chronyd &>/dev/null; then
  if which chronyc &>/dev/null; then
    { hour=$(date '+%H')
      if [[ ! -f /dev/shm/test_chrony.last || "$hour" != "$(</dev/shm/test_chrony.last)" ]]; then
        full=1
        cat >/dev/shm/test_chrony.last <<<"$hour"
      fi
      echo "D;$DT;$ULSHOSTNAME;System;Chrony;"
      chronyc tracking | awk -v full=$full -F ' *: *' '
        function flformat(f)
        { d = 4 - log(f)/2.3
          if( d < 0 )
            d = 0
          return sprintf("%0.*f", d, f)
        }
        $1 == "Reference ID" && full { printf("V;;;;;RefId;%s;_\n", $2) }
        $1 == "Stratum"      && full { printf("V;;;;;Stratum;%d;#\n", $2) }
        $1 == "System time"    { if( $2 ~ "slow" )
                                   printf("V;;;;;TimeDiff;-%s;s\n", flformat(0.0+$2))
                                 else
                                   printf("V;;;;;TimeDiff;%s;s\n", flformat(0.0+$2))
                               }
        '
      chronyc sources | awk '
        function flformat(f)
        { d = 3 - log(f)/2.3
          if( d < 0 )
            d = 0
          return sprintf("%0.*f", d, f)
        }
        BEGIN { cnt = 0
                unreach = 0
                maxdiff = 0
              }
        header { if( $1 ~ "^[=^]")
                 { cnt++
                   if( $1 ~ "^.[?]" )
                     unreach++
                 }
                 split($0, a, "[][] *")
                 if( a[2] ~ "ns$" )
                   d = (0.0+a[2])/1000000000
                 else if( a[2] ~ "us$" )
                   d = (0.0+a[2])/1000000
                 else if( a[2] ~ "ms$" )
                   d = (0.0+a[2])/1000
                 else if( a[2] ~ "s$" )
                   d = (0.0+a[2])
                 else if( a[2] ~ "m$" )
                   d = (0.0+a[2])*60
                 else if( a[2] ~ "h$" )
                   d = (0.0+a[2])*3600
                 if( d < 0 )
                   d = -d
                 if( d > maxdiff )
                   maxdiff = d
               }
        $1 ~ "========" { header = 1 }
        END { printf("V;;;;;Sources;%d;#\n", cnt)
              printf("V;;;;;Reachable;%d;#\n", cnt-unreach)
              printf("V;;;;;Unreachable;%d;#\n", unreach)
              printf("V;;;;;MaxTimeDiff;%s;s\n", flformat(maxdiff))
            }'
    } | send_test_tab
  fi
fi
