#!/usr/bin/env bash
# ==============================================================================
# Proprietary License -- All Rights Reserved
#
# Copyright (c) 2017 Dealerdirect B.V.
# ==============================================================================

set -o errexit  # Exit script when a command exits with non-zero status.
set -o errtrace # Exit on error inside any functions or sub-shells.
set -o nounset  # Exit script on use of an undefined variable.
set -o pipefail # Return exit status of the last command in the


readonly EX_OK=0 # Successful termination
readonly EX_DEPENDENCY_MISSING=66 # A dependency could not be found
readonly EX_COULD_NOT_DOWNLOAD=67 # Could not download the swagger-codegen-cli JAR file
readonly EX_COULD_NOT_GENERATE=68 # The swagger-codegen-cli encountered an error while generating

readonly g_sProjectRoot="$( cd "$( dirname "$( dirname "${BASH_SOURCE[0]}" )" )" && pwd )"
readonly g_sSwaggerJarFile="${PWD}/bin/swagger-codegen-cli.jar"
readonly g_sSwaggerJarUrl='http://central.maven.org/maven2/io/swagger/swagger-codegen-cli/2.2.2/swagger-codegen-cli-2.2.2.jar'

isInstalled() {
    return $(command -v "${1}" >/dev/null 2>&1);
}

printError() {
  echo
  echo " !     ERROR: $*" 1>&2
  echo
}

printStatus() {
    echo "-----> $*"
}

printTopic() {
    echo
    echo "=====> $*"
}

validate_dependency() {

    local -r sSubject="${1}"

    printStatus "Checking ${sSubject} is available..."

    if ! isInstalled "${sSubject}";then
        printError "Could not find '${sSubject}'. Aborting."
        exit ${EX_DEPENDENCY_MISSING}
    fi
}

validate_swagger_jar() {
    printTopic 'Checking Swagger Generator is available...'

    if [[  -f "${g_sSwaggerJarFile}" ]];then
        printStatus 'Swagger JAR file found'
    else
        printStatus 'Could not find Swagger JAR file'
        printStatus "Downloading from '${g_sSwaggerJarUrl}'"

        wget "${g_sSwaggerJarUrl}" -O "${g_sSwaggerJarFile}" || (
            printError 'Download failed. Aborting.'
            exit ${EX_COULD_NOT_DOWNLOAD}
        )
    fi
}

pre_generate() {

    printTopic 'Validating dependencies...'

    validate_dependency 'java'

    validate_dependency 'php'

    validate_dependency 'composer'

    validate_swagger_jar

    printStatus 'Making sure all PHP dependencies are installed'

    composer install
}

post_generate() {

    printTopic 'Cleaning up unwanted files'

    rm --force "${g_sProjectRoot}/.travis.yml"
    rm --force "${g_sProjectRoot}/.swagger-codegen-ignore"
    rm --force "${g_sProjectRoot}/.php_cs"
    rm --force "${g_sProjectRoot}/.php_cs.cache"
    rm --force "${g_sProjectRoot}/git_push.sh"
}

generate() {
    printTopic 'Generating SDK'

    printStatus 'Generating PHP files'
    java -jar "${g_sSwaggerJarFile}" generate \
        --input-spec "${g_sProjectRoot}/swagger.json" \
        --lang 'php' \
        --output "${g_sProjectRoot}/" \
        --config "${g_sProjectRoot}/config.json" || (
            printError 'Could not generate SDK'
            exit ${EX_COULD_NOT_GENERATE}
        )

    printStatus 'Cleaning up code'

    # Because the fixer given an error code on success we just ignore this piece of crap.
    php "${g_sProjectRoot}/vendor/bin/php-cs-fixer" 'fix' || true
}

generate_email_service_sdk() {

    pre_generate

    generate

    post_generate

    echo 'Done.'

    exit ${EX_OK}
}

if [ "${BASH_SOURCE[0]}" == "${0}" ]; then
    # direct call to file
    generate_email_service_sdk
fi  # else file is included from another script

#EOF
