import glob
import json

from oslo.config import cfg

from st2common import log as logging
from st2common.exceptions.db import StackStormDBObjectNotFoundError
from st2common.models.api.action import ActionTypeAPI
from st2common.persistence.action import (ActionType, Action)
from st2common.models.db.action import ActionDB
from st2common.util.action_db import get_actiontype_by_name

LOG = logging.getLogger(__name__)


def register_action_types():
    ACTION_TYPES = [{'name': 'shell',
                     'description': 'A bash shell action type.',
                     'enabled': True,
                     'runner_parameters': {'shell': '/usr/bin/bash',
                                           'cmd': None},
                     'runner_module': 'st2actionrunner.runners.shellrunner'},

                    {'name': 'remote-exec-sysuser',
                     'description': 'A remote execution action type with a fixed system user.',
                     'enabled': True,
                     'runner_parameters': {'hosts': None,
                                           'parallel': None,
                                           'sudo': None,
                                           'user': None,
                                           'cmd': None,
                                           'remotedir': None},
                     'runner_module': 'st2actionrunner.runners.fabricrunner'},

                    {'name': 'http-runner',
                     'description': 'A HTTP client for running HTTP actions.',
                     'enabled': True,
                     'runner_parameters': {'url': None,
                                           'headers': None,
                                           'cookies': None,
                                           'proxy': None,
                                           'redirects': None},
                     'runner_module': 'st2actionrunner.runners.httprunner'}]

    LOG.debug('Registering actiontypes')

    for fields in ACTION_TYPES:
        actiontype_db = None
        name = fields['name']
        try:
            actiontype_db = get_actiontype_by_name(name)
        except StackStormDBObjectNotFoundError:
            LOG.debug('ActionType "%s" does not exist in DB', name)
        else:
            continue

        if actiontype_db is None:
            actiontype = ActionTypeAPI()
            for (key, value) in fields.items():
                LOG.debug('actiontype name=%s field=%s value=%s', name, key, value)
                setattr(actiontype, key, value)

            actiontype_api = ActionTypeAPI.to_model(actiontype)
            LOG.debug('ActionType after field population: %s', actiontype_api)
            actiontype_db = ActionType.add_or_update(actiontype_api)
            LOG.debug('created actiontype name=%s in DB. Object: %s', name, actiontype_db)

    LOG.debug('Registering actiontypes complete')


def register_actions():
    actions = glob.glob(cfg.CONF.actions.modules_path + '/*.json')
    for action in actions:
        LOG.debug('Loading action from %s', action)
        with open(action, 'r') as fd:
            try:
                content = json.load(fd)
            except:
                LOG.exception('Unable to load action from %s.', action)
                continue
            try:
                model = Action.get_by_name(str(content['name']))
            except:
                model = ActionDB()
            model.name = str(content['name'])
            model.description = str(content['description'])
            model.enabled = bool(content['enabled'])
            model.entry_point = str(content['entry_point'])
            try:
                model.runner_type = get_actiontype_by_name(str(content['runner_type']))
            except StackStormDBObjectNotFoundError:
                LOG.exception('Failed to register action %s as runner %s was not found',
                              model.name, str(content['runner_type']))
                continue
            model.parameters = dict(content['parameters'])
            model = Action.add_or_update(model)
            LOG.debug('Added action %s from %s.', model.name, action)


def init_model():
    pass

@@ -523,30 +523,60 @@
  'A 
-bash shell action type
+local execution action type with a fixed system user
 .',%0A
@@ -661,31 +661,264 @@
 : %7B'
-shell': '/usr/bin/bash'
+hosts': 'localhost',%0A                                           'parallel': 'False',%0A                                           'sudo': 'False',%0A                                           'user': None,%0A                                           'cmd': None
 ,%0A  
@@ -955,27 +955,33 @@
            '
-cmd
+remotedir
 ': None%7D,%0A  
@@ -1041,21 +1041,22 @@
 runners.
-shell
+fabric
 runner'%7D
@@ -2958,32 +2958,53 @@
 actiontype_api)%0A
+            try:%0A    
             acti
@@ -3048,32 +3048,36 @@
 actiontype_api)%0A
+    
             LOG.
@@ -3150,16 +3150,124 @@
 type_db)
+%0A            except:%0A                LOG.exception('Unable to register action_type %25s.', actiontype%5B'name'%5D)
 %0A%0A    LO

Add fabric based localrunner