#!/usr/bin/env python
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import json
import logging
import os
import subprocess
import sys

WORKING_DIR = os.environ.get('HEAT_ATOMIC_WORKING',
                             '/var/lib/heat-config/heat-config-atomic')
ATOMIC_CMD = os.environ.get('HEAT_ATOMIC_CMD', 'atomic')


def prepare_dir(path):
    if not os.path.isdir(path):
        os.makedirs(path, 0o700)


def build_response(deploy_stdout, deploy_stderr, deploy_status_code):
    return {
        'deploy_stdout': deploy_stdout,
        'deploy_stderr': deploy_stderr,
        'deploy_status_code': deploy_status_code,
    }


def main(argv=sys.argv):
    log = logging.getLogger('heat-config')
    handler = logging.StreamHandler(sys.stderr)
    handler.setFormatter(
        logging.Formatter(
            '[%(asctime)s] (%(name)s) [%(levelname)s] %(message)s'))
    log.addHandler(handler)
    log.setLevel('DEBUG')

    c = json.load(sys.stdin)

    prepare_dir(WORKING_DIR)
    os.chdir(WORKING_DIR)

    env = os.environ.copy()

    input_values = dict((i['name'], i['value']) for i in c['inputs'])

    stdout, stderr = {}, {}
    config = c.get('config', '')
    if not config:
        log.debug("No 'config' input found, nothing to do.")
        json.dump(build_response(stdout, stderr, 0), sys.stdout)
        return

    atomic_subcmd = config.get('command', 'install')
    image = config.get('image')

    if input_values.get('deploy_action') == 'DELETE':
        cmd = [
            'uninstall',
            atomic_subcmd,
            image
        ]
        subproc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE, env=env)
        stdout, stderr = subproc.communicate()

        json.dump(build_response(stdout, stderr, subproc.returncode), sys.stdout)
        return

    install_cmd = config.get('installcmd', '')
    name = config.get('name', c.get('id'))

    cmd = [
        ATOMIC_CMD,
        atomic_subcmd,
        image,
        '-n %s' % name
    ]

    if atomic_subcmd == 'install':
        cmd.extend([install_cmd])

    privileged = config.get('privileged', False)

    if atomic_subcmd == 'run' and privileged:
        cmd.extend(['--spc'])

    log.debug('Running %s' % cmd)

    subproc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    stdout, stderr = subproc.communicate()

    log.debug(stdout)
    log.debug(stderr)

    if subproc.returncode:
        log.error("Error running %s. [%s]\n" % (cmd, subproc.returncode))
    else:
        log.debug('Completed %s' % cmd)

    json.dump(build_response(stdout, stderr, subproc.returncode), sys.stdout)

if __name__ == '__main__':
    sys.exit(main(sys.argv))
