#!/usr/bin/env python3

import logging
import os
import subprocess
import sys

OK = 0
WARNING = 1
CRITICAL = 2
UNKNOWN = 3

NTPQ = ['/usr/bin/ntpq','-np']

version = '1.0.0'
nagioslogger = logging.getLogger(__name__)

def ntpq(env = None):
  response = subprocess.run(NTPQ, stdout=subprocess.PIPE, env=env)
  if response.returncode != 0:
    raise Exception('Could not run ntpq command')
  stdout = response.stdout.decode('utf-8').split('\n')
  lines = list()
  count = 0
  for line in stdout:
    count = count+1
    if count < 3: # remove first two lines
      continue;
    args = line.split()
    if len(args) > 3 and args[3] != 'p': # remove all pools
      lines.append(args[0])
  return lines

def main():
  log_level = logging.INFO
  log_file = None
  logging.basicConfig(filename=log_file,format='%(message)s',level=log_level)

  try:
    count = 0
    response = ntpq()
    if len(response) == 0:
      nagioslogger.info("CRITICAL: NTP Quene is not filled")
      sys.exit(CRITICAL)
    else:
      nagioslogger.info("OK: NTP Quene is filled: %s",len(response))
      sys.exit(OK)

  except Exception as e:
    nagioslogger.critical('UNKNOWN: NTP Queue check failed: %s' % e)
    sys.exit(UNKNOWN)

if __name__ == "__main__":
  main()
