#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# 2012-2014 Nico Schottelius (nico-cinv at schottelius.org)
#
# This file is part of cinv.
#
# cinv 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 3 of the License, or
# (at your option) any later version.
#
# cinv 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 cinv. If not, see <http://www.gnu.org/licenses/>.
#
#

import os
import subprocess

try:
    with open(os.devnull, 'w') as devnull:
        here = os.path.dirname(os.path.realpath(__file__))
        VERSION = subprocess.check_output(
                    'cd "%s" && git describe' % here,
                    stderr=devnull, shell=True).decode('utf-8')
except:
    VERSION     = "2.0.0 (very soon)"

def commandline():
    """Parse command line"""
    import argparse

    parser = {}

    ######################################################################
    # Options _all_ parsers have in common
    parser['loglevel'] = argparse.ArgumentParser(add_help=False)
    parser['loglevel'].add_argument('-d', '--debug',
        help='Set log level to debug', action='store_true',
        default=False)
    parser['loglevel'].add_argument('-v', '--verbose',
        help='Set log level to info, be more verbose',
        action='store_true', default=False)

    ######################################################################
    # Main subcommand parser
    parser['main'] = argparse.ArgumentParser(description='cinv ' + VERSION,
        parents=[parser['loglevel']])
    parser['main'].add_argument('-V', '--version',
        help='Show version', action='version',
        version='%(prog)s ' + VERSION)
    parser['main'].epilog = "Get cinv at http://www.nico.schottelius.org/software/cinv/"
    parser['mainsub'] = parser['main'].add_subparsers(title="Commands")

    ######################################################################
    # net-ipv4
    import cinv.netipv4
    parser['net-ipv4'] = {}
    parser['net-ipv4']['main'] = parser['mainsub'].add_parser('net-ipv4', 
        parents=[parser['loglevel']])
    cinv.netipv4.NetIPv4.commandline_args(parser['net-ipv4']['main'], [parser['loglevel']])

    ######################################################################
    # host
    import cinv.host
    parser['host'] = {}
    parser['host']['main'] = parser['mainsub'].add_parser('host', 
        parents=[parser['loglevel']])
    cinv.host.Host.commandline_args(parser['host']['main'], [parser['loglevel']])

    ######################################################################
    # mac
    import cinv.mac
    parser['mac'] = {}
    parser['mac']['main'] = parser['mainsub'].add_parser('mac', 
        parents=[parser['loglevel']])
    cinv.mac.Mac.commandline_args(parser['mac']['main'], [parser['loglevel']])


    ######################################################################
    # process
    import cinv.process
    parser['process'] = {}
    parser['process']['main'] = parser['mainsub'].add_parser('process', 
        parents=[parser['loglevel']])
    cinv.process.Process.commandline_args(parser['process']['main'], [parser['loglevel']])

    args = parser['main'].parse_args(sys.argv[1:])

    ######################################################################
    # Loglevels - for all areas
    if args.verbose:
        logging.root.setLevel(logging.INFO)
    if args.debug:
        logging.root.setLevel(logging.DEBUG)

    log.debug(args)

    try:
        a = getattr(args, "func")
    except AttributeError:
        parser['main'].print_help()
        sys.exit(0)

    try:
        args.func(args)
    except cinv.Error as e:
        log.error(e)
        return 1

    return 0

def commandline_main(args):
    pass


if __name__ == "__main__":
    # Sys is needed for sys.exit()
    import sys

    cinvpythonversion = '3.2'
    if sys.version < cinvpythonversion:
        print('Sexy requires Python >= ' + cinvpythonversion, 
            file=sys.stderr)
        sys.exit(1)

    try:
        import logging
        import os

        # Ensure our /lib/ is included into PYTHON_PATH
        sys.path.insert(0, os.path.abspath(
                os.path.join(os.path.dirname(os.path.realpath(__file__)), '../lib')))

        log = logging.getLogger("cinv")
        logging.basicConfig(format='%(levelname)s: %(message)s')

        exit_code = commandline()

    except KeyboardInterrupt:
        pass

    sys.exit(exit_code)
