#!/usr/bin/env python
# coding: utf-8
"""Usage:
tues-provider-nagios [-a] [--host=<host>] [--socket=<socket>] [<service-expr>] [<host-expr>]

This provider requires the check_mk livestatus plugin

Options:
  -a                             Also consider services in OK state
  <service-expr>                 A regluar expression matching the service description
  <host-expr>                    A regluar expression matching the host name
  --host=<host>                  The hostname of the nagios server
  --socket=<socket>              The path to the livestatus socket on the nagios server
"""

from __future__ import print_function

import os as _os
import subprocess as _sp

import docopt as _docopt


def hosts(host, socket, service_expr=None, host_expr=None, consider_all_states=False):
    proc = _sp.Popen('ssh {0} "unixcat {1}"'.format(host, socket), shell=True, stdin=_sp.PIPE, stdout=_sp.PIPE)
    proc.stdin.write(b'GET services\nColumns: host_name\n')
    if not consider_all_states:
        proc.stdin.write(b'Filter: state != 0\n')

    if service_expr is not None:
        proc.stdin.write('Filter: description ~~ {0}\n'.format(service_expr).encode('utf-8'))

    if host_expr is not None:
        proc.stdin.write('Filter: host_name ~~ {0}\n'.format(host_expr).encode('utf-8'))

    proc.stdin.close()
    try:
        return set(_.decode('utf-8').strip() for _ in proc.stdout)
    finally:
        proc.terminate()


if __name__ == '__main__':
    args = _docopt.docopt(__doc__)
    nagios_host = args.get('--host') or _os.environ.get('NAGIOS_HOST', 'nagios')
    livestatus_socket = (
        args.get('--socket')
        or _os.environ.get('NAGIOS_LIVESTATUS_SOCKET', '/var/lib/nagios3/rw/livestatus')
    )

    print(
        '\n'.join(
            hosts(
                nagios_host,
                livestatus_socket,
                args['<service-expr>'],
                args['<host-expr>'],
                args.get('-a', False),
            ),
        ),
    )
