#!/usr/bin/python

"""
wrapper script of /usr/bin/docker for mesos slave. We can do some other
stuff before mesos slave execute docker
"""

from os.path import join, abspath
import sys
import subprocess
import traceback
import logging
import logging.config

ROOT_DIR = abspath(join(__file__, '../../'))
sys.path.insert(0, ROOT_DIR)

from luna import private_net
# from luna import force_pull, overcommit
from luna import dns
from luna import volume
from luna import log_driver
from luna import sandbox
from luna import overcommit
from luna.wrapper import chain
import settings
import importlib

ACTION_WRAPPER = {
    'run': chain([globals()[x].Run for x in settings.WRAPPERS['run'] if x != '']),
    'wait': chain([globals()[x].Wait for x in settings.WRAPPERS['wait'] if x != ''])
}

logger = logging.getLogger(__name__)


class EmptyWrapper(object):

    def __init__(self, args):
        pass


if __name__ == '__main__':
    "this is docker wrapper"
    if len(sys.argv) < 2:
        print 'action is missing'
        print 'usage: docker ACTION ...'
        sys.exit(1)

    # log = open('/var/log/luna.log', 'a')
    # log.write(' '.join(sys.argv))
    # log.write('\n')
    # log.close()
    action = sys.argv[1] if sys.argv[1] != '-H' else sys.argv[3]
    cli_args = sys.argv[2:] if sys.argv[1] != '-H' else sys.argv[4:]
    logger.info("luna/docker %s" % (' '.join(sys.argv[1:] if sys.argv[1] != '-H' else sys.argv[3:])))
    if action in ACTION_WRAPPER:
        wrapper_builder = ACTION_WRAPPER[action]
    else:
        wrapper_builder = EmptyWrapper

    try:
        wrapper = wrapper_builder(cli_args)

        if hasattr(wrapper, 'pre_run'):
            wrapper.pre_run()

        if hasattr(wrapper, 'to_args'):
            args = wrapper.to_args()
        else:
            args = cli_args
        logger.info("docker %s %s" % (action, ' '.join(args)))
        result_code = subprocess.call(['docker', action] + args,
                                      stdout=sys.stdout, stderr=sys.stderr)
    except Exception:
        traceback.print_exc()
        sys.exit(255)

    try:
        # run injection codes after docker command
        # whatever the result of indection code, script's result code alway be docker command's result
        if hasattr(wrapper, 'post_run'):
            wrapper.post_run()
    except Exception, e:
        traceback.print_exc()

    sys.exit(result_code)
