#!/usr/bin/env python3
#
#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation; either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License along
#   with this program; if not, write to the Free Software Foundation, Inc.,
#   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import subprocess
import re
import sys
import os

os.environ["PATH"] = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/sbin:/usr/X11R6/bin"


cmd = "ntpq -n -c peers"

if len(sys.argv) != 2:
    print(sys.argv[0] + " offset|jitter|delay|count")
    sys.exit(1)

what = sys.argv[1]

server_count = 0

process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, err = process.communicate()

for line in out.decode('utf8').splitlines():
    m = re.match(
        r"^(?P<mode>\*|\+|o|x|\.|\#)(.+?)\s+.*(?P<delay>-?\d+\.?\d*)\s+(?P<offset>-?\d+\.?\d*)\s+(?P<jitter>-?\d+\.?\d*)$",
        line)
    if not m:
        continue

    if sys.stderr.isatty():
        sys.stderr.write("match:%s\n" % line.rstrip())
    server_count += 1

    if what in ["offset", "jitter", "delay"] and m.group("mode") == "*":
        sys.stdout.write(m.group(what))

if what == "count":
    sys.stdout.write(str(server_count))

# vim: ai et ts=2 shiftwidth=2 expandtab
