#!/usr/bin/env bash

COMPOSER=`which composer`

set -e

CURRENTDIR=$(cd $(dirname $0); echo $PWD)
cd ${CURRENTDIR}

#
# Export your php-binary to variable PHP to use multiple php versions
#
if [ "" == "${PHP}" ]; then
    PHP=`which php`
elif [ "" != "${COMPOSER}" ]; then
    COMPOSER="${PHP} ${COMPOSER}"
fi

if [ "" == "${COMPOSER}" ]; then

    if [ ! -f "composer.phar" ]; then

        COMPOSER_EXPECTED_SIGNATURE=$(curl -sS https://composer.github.io/installer.sig)
        ${PHP} -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
        COMPOSER_ACTUAL_SIGNATURE=$(${PHP} -r "echo hash_file('SHA384', 'composer-setup.php');")

        if [ "${COMPOSER_EXPECTED_SIGNATURE}" != "${COMPOSER_ACTUAL_SIGNATURE}" ]
        then
            >&2 echo 'ERROR: Invalid composer installer signature'
            rm composer-setup.php
            exit 1
        fi

        ${PHP} composer-setup.php --quiet
        rm composer-setup.php

    fi

    COMPOSER="${PHP} ${CURRENTDIR}/composer.phar"
    ${COMPOSER} self-update
fi

# Move vendor folder back
function cleanup {
    if [ -d vendor.tmp ]; then
        rm -rf vendor
        mv vendor.tmp vendor
    fi
}
trap cleanup EXIT ERR SIGINT SIGTERM

if [ -d vendor ]; then
    rm -rf vendor.tmp
    mv vendor vendor.tmp
fi

# Composer install for service application
${COMPOSER} install --no-scripts --no-dev

npm run build

# Build zip file for deployment
mkdir -p build
rm -f build/eb.zip
zip -q -r build/eb.zip \
.ebextensions \
bin \
ebscripts \
packages \
public \
src \
srcBundles \
templates \
translations \
vendor \
.env \
composer.json \
composer.lock \
index.html \
README.md \
symfony.lock \
--symlinks \
\
--exclude \
*.DS_Store* \
config/packages/dev \
config/packages/test \
config/routes/dev \
config/saml/dev

echo ""
echo "use 'eb deploy --staged my-instance' to deploy application now or upload file build/eb.zip to your EBS versions"
