#!/bin/bash

set -e

[ "$DEBUG" = "true" ] && set -x

RUN_HOOKS="run-hooks"

if [ "$MAGENTO_RUN_MODE" == "production" ]; then
    echo "Cleaning directories:"

    if [ "$INSTALLATION_TYPE" == "composer" ]; then
       echo "Cleaning setup directory."
       rm -rf $MAGENTO_ROOT/setup/*
    fi

    echo "Cleaning vendor directory."
    rm -rf $MAGENTO_ROOT/vendor/*

    echo "Cleaning generated directory."
    rm -rf $MAGENTO_ROOT/generated/*

    echo "Removing app/etc/env.php file"
    rm -f  $MAGENTO_ROOT/app/etc/env.php
fi

echo "Installing dependencies."

composer --working-dir=$MAGENTO_ROOT install --no-suggest --no-ansi --no-interaction --no-progress --prefer-dist

echo "Running \"build\" hook."

$RUN_HOOKS build

if [ "$MAGENTO_RUN_MODE" == "production" ]; then
    echo "Setting file permissions."

    chown -R www:www $MAGENTO_ROOT

    find $MAGENTO_ROOT/pub -type f -exec chmod 664 {} \;
    find $MAGENTO_ROOT/pub -type d -exec chmod 775 {} \;
fi

echo "Building complete."
