#!/usr/bin/python2
# -*- coding: utf-8 -*-

# SPDX-License-Identifier: BSD-2-clause
'''\
Any keystroke causes a poll and update. Keystroke commands:

'a': Change peer display to apeers mode, showing association IDs.
'd': Toggle detail mode (some peer will be reverse-video highlighted when on).
'j': Select next peer (in select mode); arrow down also works.
'k': Select previous peer (in select mode); arrow up also works.
'm': Disable peers display, showing only MRU list
'n': Toggle display of hostnames (vs. IP addresses).
'o': Change peer display to opeers mode, showing destination address.
'p': Change peer display to default mode, showing refid.
'q': Cleanly terminate the program.
's': Toggle display of only reachable hosts (default is all hosts).
'u': Toggle display of units.
'w': Toggle wide mode.
'x': Cleanly terminate the program.
' ': Rotate through a/n/o/p display modes.
'+': Increase debugging level.  Output goes to ntpmon.log
'-': Decrease debugging level.
'?': Display helpscreen.
'''

from __future__ import print_function, division

import sys
import time
import getopt

try:
    import ntp.packet
    import ntp.util
    import ntp.ntpc
    import ntp.version
    import ntp.control
    import ntp.magic
except ImportError as e:
    sys.stderr.write(
        "ntpmon: can't find Python NTP library -- check PYTHONPATH.\n")
    sys.stderr.write("%s\n" % e)
    sys.exit(1)


try:
    import locale
except ImportError as e:
    sys.stderr.write(
        "ntpmon: can't find Python locale library -- check PYTHONPATH.\n")
    sys.stderr.write("%s\n" % e)
    sys.exit(1)

try:
    import curses
except ImportError as e:
    sys.stderr.write(
        "ntpmon: can't find Python curses library -- check PYTHONPATH.\n")
    sys.stderr.write("%s\n" % e)
    sys.exit(1)

stdscr = None


def iso8601(t):
    "ISO8601 string from Unix time, including fractional second."
    return time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(time.time()))


def statline(_peerlist, _mrulist, nyquist):
    "Generate a status line"
    # We don't use stdversion here because the presence of a date is confusing
    leader = sysvars['version'][0]
    if span.entries:
        trailer = "Last update: %s (%s)" \
                  % (iso8601(span.entries[0].last),
                     ntp.util.PeerSummary.prettyinterval(nyquist))
    else:
        trailer = ""
    spacer = (peer_report.termwidth - len(leader) - len(trailer)) * " "
    return leader + spacer + trailer


def peer_detail(variables, showunits=False):
    "Show the things a peer summary doesn't, cooked slightly differently"
    # All of an rv display except refid, reach, delay, offset, jitter.
    # One of the goals here is to emit field values at fixed positions
    # on the 2D display, so that changes in the details are easier to spot.
    vcopy = {}
    vcopyraw = {}
    vcopy.update(variables)
    # Need to separate the casted from the raw
    for key in vcopy.keys():
        vcopyraw[key] = vcopy[key][1]
        vcopy[key] = vcopy[key][0]
    vcopy["leap"] = ("no-leap", "add-leap", "del-leap",
                     "unsync")[vcopy["leap"]]
    for fld in ('xmt', 'rec', 'reftime'):
        if fld not in vcopy:
            vcopy[fld] = "***missing***"
        else:
            vcopy[fld] = ntp.util.rfc3339(ntp.ntpc.lfptofloat(vcopy[fld]))
    if showunits:
        for name in ntp.util.MS_VARS:
            if name in vcopy:
                vcopy[name] = ntp.util.unitify(vcopyraw[name],
                                               ntp.util.UNIT_MS,
                                               width=None)
        for name in ntp.util.PPM_VARS:
            if name in vcopy:
                vcopy[name] = ntp.util.unitify(vcopyraw[name],
                                               ntp.util.UNIT_PPM,
                                               width=None)
        for name in ntp.util.S_VARS:
            if name in vcopy:
                vcopy[name] = ntp.util.unitify(vcopyraw[name],
                                               ntp.util.UNIT_S,
                                               width=None)
        vcopy['filtdelay'] = ntp.util.stringfiltcooker(vcopyraw['filtdelay'])
        vcopy['filtoffset'] = ntp.util.stringfiltcooker(vcopyraw['filtoffset'])
        vcopy['filtdisp'] = ntp.util.stringfiltcooker(vcopyraw['filtdisp'])
    else:
        vcopy['filtdelay'] = vcopy['filtdelay'].replace(' ', '\t')
        vcopy['filtoffset'] = vcopy['filtoffset'].replace(' ', '\t')
        vcopy['filtdisp'] = vcopy['filtdisp'].replace(' ', '\t')
    peerfmt = """\
srcadr=%(srcadr)s, srcport=%(srcport)d, dstadr=%(dstadr)s, dstport=%(dstport)s
leap=%(leap)s\treftime=%(reftime)s\trootdelay=%(rootdelay)s
stratum=%(stratum)2d\trec=%(rec)s\trootdisp=%(rootdisp)s
precision=%(precision)3d\txmt=%(xmt)s\tdispersion=%(dispersion)s
unreach=%(unreach)d, hmode=%(hmode)d, pmode=%(pmode)d, hpoll=%(hpoll)d, ppoll=%(ppoll)d, headway=%(headway)s, flash=%(flash)s, keyid=%(keyid)s
filtdelay  = %(filtdelay)s
filtoffset = %(filtoffset)s
filtdisp   = %(filtdisp)s
"""
    return peerfmt % vcopy


class Fatal(Exception):
    "Unrecoverable error."
    def __init__(self, msg):
        Exception.__init__(self)
        self.msg = msg

    def __str__(self):
        return self.msg


class OutputContext:
    def __enter__(self):
        "Begin critical region."
        locale.setlocale(locale.LC_ALL, '')
        global stdscr
        stdscr = curses.initscr()
        try:
            curses.curs_set(0)
        except curses.error:
            # VT100 terminal emulations can barf here.
            pass
        curses.cbreak()
        curses.noecho()
        stdscr.keypad(True)
        # Design decision: The most important info is nearer the
        # top of the display. Therefore, prevent scrolling.
        stdscr.scrollok(False)

    def __exit__(self, extype_unused, value_unused, traceback_unused):
        curses.endwin()

usage = '''
USAGE: ntpmon [-n] [-u] [-V] [host]
'''

if __name__ == '__main__':
    try:
        (options, arguments) = getopt.getopt(sys.argv[1:],
                                             "Vnu",
                                             ["version", "numeric", "units"])
    except getopt.GetoptError as e:
        sys.stderr.write("%s\n" % e)
        sys.stderr.write(usage)
        raise SystemExit(1)
    progname = sys.argv[0]

    showhostnames = True
    wideremote = False
    showall = True
    showpeers = True
    showunits = False
    nyquist = 1

    for (switch, val) in options:
        if switch in ("-V", "--version"):
            print("ntpmon %s" % ntp.util.stdversion())
            raise SystemExit(0)
        elif switch in ("-n", "--numeric"):
            showhostnames = False
        elif switch in ("-u", "--units"):
            showunits = True

    poll_interval = 1
    helpmode = selectmode = detailmode = False
    selected = -1
    peer_report = ntp.util.PeerSummary(displaymode="peers",
                                       pktversion=ntp.magic.NTP_VERSION,
                                       showhostnames=showhostnames,
                                       wideremote=wideremote,
                                       showunits=showunits,
                                       termwidth=80,
                                       debug=0)
    mru_report = ntp.util.MRUSummary(showhostnames)
    try:
        session = ntp.packet.ControlSession()
        session.openhost(arguments[0] if arguments else "localhost")
        sysvars = session.readvar(raw=True)
        with OutputContext() as ctx:
            while True:
                stdscr.clear()
                stdscr.addstr(0, 0, u"".encode('UTF-8'))
                if helpmode:
                    stdscr.addstr(unicode(__doc__).encode('UTF-8'))
                    tempStr = u"\nPress any key to resume monitoring"
                    stdscr.addstr(tempStr.encode('UTF-8'))
                    stdscr.refresh()
                    stdscr.timeout(-1)
                else:
                    if showpeers:
                        try:
                            peers = session.readstat()
                        except ntp.packet.ControlException as e:
                            raise Fatal(e.message)
                        except IOError as e:
                            raise Fatal(e.strerror)
                        strconvert = unicode(peer_report.header() + "\n")
                        stdscr.addstr(strconvert.encode('UTF-8'),
                                      curses.A_BOLD)
                    else:
                        peer_report.polls = [1]  # Kluge!
                        peers = []
                    if showpeers and len(peers) == 0:
                        raise Fatal("no peers reported")
                    try:
                        initphase = False
                        for (i, peer) in enumerate(peers):
                            if (not showall
                                and not (
                                    ntp.control.CTL_PEER_STATVAL(peer.status)
                                    & (ntp.control.CTL_PST_CONFIG |
                                       ntp.control.CTL_PST_REACH))):
                                continue
                            try:
                                variables = session.readvar(peer.associd,
                                                            raw=True)
                            except ntp.packet.ControlException as e:
                                raise Fatal(e.message + "\n")
                            except IOError as e:
                                raise Fatal(e.strerror)
                            except IndexError:
                                raise Fatal(
                                    "no 'hpoll' variable in peer response")
                            if not variables:
                                continue
                            if selectmode and selected == i:
                                retained = variables
                                hilite = curses.A_REVERSE
                            else:
                                hilite = curses.A_NORMAL
                            data = peer_report.summary(session.rstatus,
                                                       variables,
                                                       peer.associd)
                            data = unicode(data).encode('UTF-8')
                            stdscr.addstr(data, hilite)
                            if 'INIT' in variables['refid']:
                                initphase = True

                        # Now the MRU report
                        limit = stdscr.getmaxyx()[0] - len(peers)
                        span = session.mrulist(variables={'recent': limit})
                        mru_report.now = time.time()

                        # After init phase use Nyquist-interval
                        # sampling - half the smallest poll interval
                        # seen in the last cycle, rounded up to 1
                        # second.
                        if not initphase:
                            nyquist = int(min(peer_report.intervals()) / 2)
                            nyquist = 1 if nyquist == 0 else nyquist
                            if session.debug:
                                session.logfp.write("nyquist is %d\n" %
                                                    nyquist)
                        # The status line
                        sl = statline(peer_report, mru_report, nyquist)
                        strconvert = unicode(sl + "\n")
                        stdscr.addstr(strconvert.encode('UTF-8'),
                                      curses.A_REVERSE | curses.A_DIM)
                        if detailmode:
                            if ntp.util.PeerSummary.is_clock(retained):
                                dtype = ntp.ntpc.TYPE_CLOCK
                            else:
                                dtype = ntp.ntpc.TYPE_PEER
                            sw = ntp.ntpc.statustoa(dtype,
                                                    peers[selected].status)
                            strconvert = u"assoc=%d: %s\n".encode('UTF-8')
                            stdscr.addstr(strconvert
                                          % (peers[selected].associd, sw))
                            strconvert = peer_detail(retained, showunits)
                            stdscr.addstr(strconvert.encode('UTF-8'))
                            try:
                                clockvars = session.readvar(
                                    peers[selected].associd,
                                    opcode=ntp.control.CTL_OP_READCLOCK,
                                    raw=True)
                                strconvert = ntp.util.cook(clockvars,
                                                           showunits)
                                stdscr.addstr(strconvert.encode('UTF-8'))
                            except ntp.packet.ControlException as e:
                                pass
                        elif span.entries:
                            strconvert = ntp.util.MRUSummary.header + "\n"
                            stdscr.addstr(unicode(strconvert).encode('UTF-8'),
                                          curses.A_BOLD)
                            for entry in reversed(span.entries):
                                strcon = mru_report.summary(entry) + "\n"
                                stdscr.addstr(unicode(strcon).encode('UTF-8'))
                    except curses.error:
                        # An addstr overran the screen, no worries
                        pass
                    # Display all
                    stdscr.refresh()
                    stdscr.timeout(nyquist * 1000)
                try:
                    helpmode = False
                    key = stdscr.getkey()
                    if key == 'q' or key == 'x':
                        raise SystemExit(0)
                    elif key == 'a':
                        peer_report.displaymode = 'apeers'
                    elif key == 'd':
                        if not selectmode:
                            selected = 0
                        selectmode = not selectmode
                        detailmode = not detailmode
                        showpeers = True  # detail + hide peers == crash
                    elif key == 'm':
                        showpeers = not showpeers
                        detailmode = False  # detail + hide peers == crash
                    elif key == 'n':
                        peer_report.showhostnames = \
                            not peer_report.showhostnames
                        mru_report.showhostnames = not mru_report.showhostnames
                    elif key == 'o':
                        peer_report.displaymode = 'opeers'
                    elif key == 'p':
                        peer_report.displaymode = 'peers'
                    elif key == 's':
                        showall = not showall
                    elif key == 'u':
                        showunits = not showunits
                        peer_report.showunits = showunits
                    elif key == 'w':
                        peer_report.wideremote = not peer_report.wideremote
                    elif key == " ":
                        if peer_report.displaymode == 'peers':
                            peer_report.displaymode = 'apeers'
                        elif peer_report.displaymode == 'apeers':
                            peer_report.displaymode = 'opeers'
                        else:
                            peer_report.displaymode = 'peers'
                    elif key == 'j' or key == "KEY_DOWN":
                        if showpeers:
                            selected += 1
                            selected %= len(peers)
                    elif key == 'k' or key == "KEY_UP":
                        if showpeers:
                            selected += len(peers) - 1
                            selected %= len(peers)
                    elif key == '+':
                        if session.debug == 0:
                            session.logfp = open("ntpmon.log", "a", 1)
                            peer_report.logfp = session.logfp
                            mru_report.logfp = session.logfp
                        session.debug += 1
                        peer_report.debug = session.debug
                        mru_report.debug = session.debug
                    elif key == '-':
                        session.debug -= 1
                        peer_report.debug = session.debug
                        mru_report.debug = session.debug
                    elif key == '?':
                        helpmode = True
                except curses.error:
                    pass
    except KeyboardInterrupt:
        print("")
    except (Fatal, ntp.packet.ControlException) as e:
        print(e)
    except IOError:
        print("Bailing out...")

# end
