#!/usr/bin/env python3
import json
import logging
import os
import subprocess
import sys

BUILD_PATH = sys.argv[1]
CACHE_PATH = sys.argv[2]

logging.basicConfig(
    level=logging.INFO,
    stream=sys.stdout,
    format='%(levelname)s: %(message)s',
)

def export_vcap_services():
    logging.debug("Executing build_vcap_services...")

    vcap_services = dict()
    vcap_services['PostgreSQL'] = [{'credentials': { 'uri': "postgres://mendix:mendix@172.17.0.2:5432/mendix" } }]

    vcap_services_str = json.dumps(vcap_services , sort_keys=True, indent=4,
        separators=(',', ': '))
    logging.debug("Set environment variable VCAP_SERVICES: \n{0}"
        .format(vcap_services_str))

    os.environ['VCAP_SERVICES'] = vcap_services_str
    os.environ["PATH"] += os.pathsep + "/opt/mendix/buildpack"

def call_buildpack_compilation():
    logging.debug("Executing call_buildpack_compilation...")
    return subprocess.call(["/opt/mendix/buildpack/bin/compile", BUILD_PATH, CACHE_PATH])

if __name__ == '__main__':
    logging.info("Mendix project compilation phase...")

    export_vcap_services()
    exit_code = call_buildpack_compilation()
    sys.exit(exit_code)
