#!/usr/bin/env python3

import argparse
import inspect
import logging
import os.path
import subprocess
import sys

from alpha.register import register

def run_action(args):
    action = args.action

    if args.action == 'install':
        assert len(args.param), 'URL not found'
        url = args.param[0]
        print('Installing recipe into /opt/alpharecipes/ from {}'.format(url))
        subprocess.call('cd /opt/alpharecipes/ && git clone {}'.format(url), shell=True)
        return
    elif args.action == 'update':
        assert len(args.param), 'Recipe name not found'
        recipe_path = os.path.join('/opt/alpharecipes', args.param[0])
        if not os.path.exists(recipe_path):
            print('Path doesn\'t exists: {}'.format(recipe_path))
            return
        print('Updating recipe /opt/alpharecipes/{}'.format(recipe_path))
        subprocess.call('cd {} && git pull origin master'.format(recipe_path), shell=True)
        return
    elif args.action == 'list':
        for name in register:
            action = register[name]
            print('{}:\n  {}'.format(name, action.__doc__))
        return

    if action in register:
        register[action](*args.param)
    else:
        for name in register:
            action = register[name]
            print('{}:\n  {}'.format(name, action.__doc__))
        raise ValueError('Action doesn\'t exists: {}'.format(args.action))


if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('action')
    parser.add_argument('param', nargs='*')
    parser.add_argument('-v', '--verbose', action='store_true')

    args = parser.parse_args()
    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    try:
        run_action(args)
    except (ValueError, RuntimeError) as e:
        sys.exit(e)
