#!/usr/bin/python

"""
Usage:
    foobar show ip route [<ip>|<ip/prefixlen>]
    foobar show ip interface [<interface>]

Help:
    help       : Show this screen
    interface  : help text for interface
    show       : show output from a command
"""

import logging
import sys
from network_docopt import NetworkDocopt, get_network_docopt_info
from subprocess import check_output


class ExampleCLI(NetworkDocopt):

    def run(self):
        NetworkDocopt.run(self)
        args = self.args

        if args['show']:
            if args['ip']:
                if args['route']:
                    if args['<ip>']:
                        print check_output(['ip', 'route', 'get', args['<ip>']])
                    elif args['<ip/prefixlen>']:
                        print check_output(['ip', 'route', 'show', args['<ip/prefixlen>']])
                    else:
                        print check_output(['ip', 'route', 'show'])
                elif args['interface']:
                    if args['<interface>']:
                        print check_output(['ip', 'addr', 'show', args['<interface>']])
                    else:
                        print check_output(['ip', 'addr', 'show'])


if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s %(levelname)7s %(filename)12s: %(message)s')
    log = logging.getLogger(__name__)

    # Color the errors and warnings in red
    logging.addLevelName(logging.ERROR, "\033[91m  %s\033[0m" % logging.getLevelName(logging.ERROR))
    logging.addLevelName(logging.WARNING, "\033[91m%s\033[0m" % logging.getLevelName(logging.WARNING))

    # network_docopt DEBUG level is very chatty, hardcode it to INFO
    logging.getLogger('network_docopt').setLevel(logging.INFO)
    # logging.getLogger('network_docopt').setLevel(logging.DEBUG)

    (print_options, ended_with_space, sys.argv) = get_network_docopt_info(sys.argv)
    cli = ExampleCLI(__doc__)

    if print_options:
        cli.print_options(ended_with_space)
    else:
        cli.run()
