#!/usr/bin/env python2

import textwrap
import argparse
import iniparse
import os
from prettytable import PrettyTable
from nagiosharder import Nagios

class NotEnough(Exception):
    pass

def cli():
    args = parse_args()
    action, object = args['action'], args['object']
    if 'config' in args:
        cfg = config(args['config'])
    user = args.get('user') or cfg.user
    password = args.get('password') or cfg.passwords
    url = args.get('url') or cfg.url
    version = args.get('version') or cfg.version
    if not all([user, password, url]):
        raise NotEnough('user, password or url were not provieded')
    nagios = Nagios(user, password, url, version)

    if action in ['ack', 'acknowledge']:
        nagios.acknowledge_service(**object.split('/'))
    if action in ['unack', 'unacknowledge']:
        nagios.unacknowledge_service(**object.split('/'))
    if action in ['mute', 'disable_notifications']:
        nagios.disable_service_notifications(**object.split('/'))
    if action in ['unmute', 'enable_notifications']:
        nagios.enable_service_notifications(**object.split('/'))
    if action == 'check':
        host, service = object.split('/')
        if service:
            nagios.schedule_service_check(service)
        else:
            nagios.schedule_host_check(service)
    if action == 'downtime':
        host, service = object.split('/')[0:2]
        end_time = object.split('/')[-1]
        if service:
            nagios.schedule_service_downtime(host, service, {'type': 'fixed', 'end_time': end_time})
        else:
            nagios.schedule_host_downtime(host, {'type': 'fixed', 'end_time': end_time})
    if action == 'problems':
        if object:
            problems = nagios.service_status('all', {'group': object})
        else:
            problems = nagios.service_status('all')
        print problems
    if action == 'status':
        rows = []
        for service in nagios.host_status(object):
            rows.append(service_row(service))
        print service_table(rows)

    if action in ['triage', 'unhandled']:
        if object:
            print nagios.service_status('all', {'group': object,
                                           'hoststatustypes': 3,
                                           'serviceprops': 42,
                                           'servicestatustypes': 28}
                                           )
        else:
            print nagios.service_status('all', {'hoststatustypes' : 3,
                                          'serviceprops' : 42,
                                          'servicestatustypes' : 28}
                                          )

def parse_args():
    parser = argparse.ArgumentParser(description='Acp. Cli.')
    parser.add_argument('action', nargs=1, type=str, metavar='action')
    parser.add_argument('object', nargs='+', type=str, metavar='object')
    parser.add_argument('-u','--user', nargs=1, metavar='user',
                                help='Nagios username')
    parser.add_argument('-p','--password', nargs=1, metavar='password',
                                help='Nagios password')
    parser.add_argument('-n','--url', nargs=1, metavar='url',
                                help='Nagios cgi url')
    parser.add_argument('-v','--version', nargs=1, metavar='version',
                                default=3, choices=[2, 3],
                                help='Nagios version')
    parser.add_argument('-c','--config', nargs=1, metavar='config_file',
                                help='Path to a config file to use')
    return vars(parser.parse_args())

def service_table(rows):
    table = PrettyTable(['Service', 'Status', 'Details'])
    table.align = 'r'
    for row in rows:
        table.add_row(row)
    return table

def service_row(service):
    if 'acknowledged' in service:
        service['status'] += "/ACK"
    if 'notifications_disabled' in service:
        service['status'] += "/MUTE"
    if 'comments_url' in service:
        service['status'] += "/COMMENT"

    return (
            service['host'] + "/" + service["service"],
            service['status'],
            textwrap.wrap(service.get('extended_info'), 40)
            )

def config(path=None):
    if not path:
        path = os.path.expanduser('~/.config/nagios-harder/config.ini')
    if os.path.exists(path):
        with open(path) as fp:
            return iniparse.INIConfig(fp)
    else:
        return iniparse.INIConfig()

if __name__ == '__main__':
    cli()
