#!/usr/bin/env python3

import os
import sys
import subprocess
import json
import base64

# Disable output buffering.
os.environ['PYTHONUNBUFFERED'] = "1"

# The list of available hooks.
available_hooks = ["build", "deploy", "post_deploy"]


# Prints a message and returns an exit code.
def error_exit(msg, code=1):
    print(msg)
    sys.exit(code)


# Gets Magento root path.
def get_magento_root():
    try:
        return str(os.environ['MAGENTO_ROOT'])
    except KeyError:
        error_exit('Environment variable MAGENTO_ROOT is not available')


# Gets set hooks by hook name.
def get_hooks(hook_name):
    try:
        application = str(os.environ['MAGENTO_CLOUD_APPLICATION'])
        content = json.loads(base64.b64decode(application).decode("utf-8"))

        return content['hooks'][hook_name]
    except Exception as exc:
        error_exit("Cannot decode string: " + str(exc))


# Main function.
def main():
    if len(sys.argv) != 2:
        error_exit("Usage: run-hooks <hook-name>")

    hook_name = str(sys.argv[1])
    if hook_name not in available_hooks:
        error_exit("The hook \"" + hook_name + "\" is not available. The list of available hooks: " + ", ".join(available_hooks))

    try:
        subprocess.check_call(
            get_hooks(hook_name),
            shell=True,
            cwd=get_magento_root()
        )
    except subprocess.CalledProcessError as exc:
        error_exit("returned non-zero exit status " + str(exc.returncode))


if __name__ == '__main__':
    main()
