#!/bin/bash
# ---
# http://gn.com.br/linux
# gncheckclock.sh - versao 1.0 (2013-07-10)
# Shell Script que Verifica a Sincronizacao do Relogio
# (bash, hwclock, tickadj, ntpd, ntpstat, stratum)
# ------
# chown root:root /etc/cron.hourly/gncheckclock.sh
# chmod 0700 /etc/cron.hourly/gncheckclock.sh
# ------
ADJTIME_FILE='/etc/adjtime'
TICKADJ_NORMAL=10000
STRATUM_MAX=8
ADMIN_EMAIL='Alterar@Aqui.Seu.Email.com.br'
LOGLEVEL_PROBLEM='emerg' # alert,emerg
# ------
VERBOSE=0
export PATH='/bin:/usr/bin:/sbin:/usr/sbin'
test -t 0 && test -t 1 && test -t 2 && VERBOSE=1
test $# -ge 1 && VERBOSE=1
unset E S M L
declare -i E=0
L='logger -s -p daemon.warning -t gncheckclock --'
# ---
if test -s "$ADJTIME_FILE" ; then
  S=`find "$ADJTIME_FILE" -mmin -200 2>/dev/null`
  if test ${#S} -le 0 ; then
    $L "$ADJTIME_FILE (hwclock): arquivo nao foi atualizado recentemnte"
    let E++
  else
    test $VERBOSE -ge 1 && echo "gncheckclock: $ADJTIME_FILE (hwclock): ok"
  fi
else
  $L "$ADJTIME_FILE (hwclock): arquivo vazio ou inexistente"
  let E++
fi
# ---
S=`tickadj 2>/dev/null`
if test ${#S} -le 0 ; then
  $L "tickadj: valor atual desconhecido"
  let E++
else
  S=${S//[^0-9]}
  if test ${#S} -le 0 ; then
    $L "tickadj: valor atual nao-numerico"
    let E++
  else
    if test $S -ne $TICKADJ_NORMAL ; then
      $L "tickadj: valor atual diferente do normal"
      let E++
    else
      test $VERBOSE -ge 1 && echo "gncheckclock: tickadj ($S): ok"
    fi
  fi
fi
# ---
S=`ntpstat 2>/dev/null`
if test $? -eq 0 ; then
  if test "_${S/unsynchronised}" != "_$S" ; then
    $L "ntpstat: sem sincronismo"
    let E++
  else
    if test "_${S/synchronised}" != "_$S" ; then
      S=${S/* at stratum }
      S=${S#[[:space:]]}
      S=${S#[[:space:]]}
      S=${S/[[:space:]]*}
      S=${S//[^0-9]}
      if test ${#S} -le 0 ; then
        $L "ntpstat: valor do stratum nao-numerico"
        let E++
      else
        if test $S -lt 0 || test $S -gt $STRATUM_MAX ; then
          $L "ntpstat: stratum muito alto"
          let E++
        else
          test $VERBOSE -ge 1 && echo "gncheckclock: ntpstat (stratum=$S): ok"
        fi
      fi
    else
      $L "ntpstat: nao sincronizado"
      let E++
    fi
  fi
else
  if test "_${S/unsynchronised}" != "_$S" ; then
    $L "ntpstat: sem sincronismo"
    let E++
  else
    $L "ntpstat: desconhecido"
    let E++
  fi
fi
# ---
if test $E -eq 0 ; then
  M="ok"
  logger -p daemon.info -t gncheckclock -- "$M"
  test $VERBOSE -ge 1 && echo "gncheckclock: $M"
else
  M="$E potenciais problemas com o relogio"
  logger -s -p daemon.$LOGLEVEL_PROBLEM  -t gncheckclock -- "$M"
fi
# ---
test $E -ne 0 || test "_`date +%H`" = _12 && {
  { echo "Subject: [`date '+%Y-%m-%d/%H:%M'`] gncheckclock: `hostname`"
    echo ''
    echo "Servidor: `hostname`"
    echo "Situacao: $M"
  } | sendmail -f "$ADMIN_EMAIL" -i "$ADMIN_EMAIL"
}
exit $E
# ---
# http://gn.com.br/linux
# ---
