#!python

import sys
import argparse

import netjsonconfig

license = """
This program 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.

This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
"""

parser = argparse.ArgumentParser(description='Converts a NetJSON DeviceConfiguration object'
                                             'to working router configurations.',
                                 epilog=license,
                                 prog='netjsonconfig')

parser.add_argument('config',
                    action='store',
                    type=str,
                    help='config file or string, must be valid NetJSON DeviceConfiguration')

parser.add_argument('--templates', '-t',
                    nargs='*',  # zero or more
                    action='store',
                    type=str,
                    default=[],
                    help='list of template config files or strings separated by space')

parser.add_argument('--backend', '-b',
                    choices=['openwrt', 'openwisp'],
                    action='store',
                    default='openwrt',
                    type=str,
                    help='Configuration backend: openwrt or openwisp')

parser.add_argument('--method', '-m',
                    choices=['generate', 'render'],
                    action='store',
                    default='generate',
                    help='Backend method to use. ("generate" creates a tar.gz, "render"'
                         'returns the entire config as a string)')

parser.add_argument('--verbose',
                    action='store_true',
                    default=False,
                    help='verbose output')

parser.add_argument('--version', '-v',
                    action='version',
                    version=netjsonconfig.get_version())

def _load(config):
    """
    if config argument does not look like a JSON string
    try to read the contents of a file
    """
    if not config.strip().startswith('{'):
        try:
            return open(config, 'r').read()
        except IOError:
            print('netjsonconfig: cannot open "{0}": file not found'.format(config))
            sys.exit(1)
    else:
        return config.strip()

args = parser.parse_args()
config = _load(args.config)
templates = [_load(template) for template in args.templates]

backends = {
    'openwrt': netjsonconfig.OpenWrt,
    'openwisp': netjsonconfig.OpenWisp
}

backend_class = backends[args.backend]
try:
    instance = backend_class(config, templates=templates)
except TypeError as e:
    print('netjsonconfig: invalid JSON passed in config or templates')
    sys.exit(2)

try:
    output = getattr(instance, args.method)()
    if output:
        print(output)
except netjsonconfig.exceptions.ValidationError as e:
    message = 'netjsonconfig: JSON Schema violation\n'
    if not args.verbose:
        info = 'For more information repeat the command using --verbose'
    else:
        info = str(e)
    print(message + info)
    sys.exit(3)
