#!/bin/sh

# entry point is latest release folder, NEW_RELEASE is the var being passed from bitbucket-pipelines.yml
# This can be manually passed by running 'bash deploy.sh 'varhere'
NEW_RELEASE=$1

ENVIRONMENT=$2

CURRENT_DIR=${PWD}
BASE_PATH=$(dirname $(dirname "$CURRENT_DIR"))

echo "Disable opcache"
sh "$BASE_PATH"/clearopcache_disable.sh || exit 1


# Symlink .env and robots files
ln -s "$BASE_PATH"/.env "$BASE_PATH"/releases/"$NEW_RELEASE"/.env
ln -s "$BASE_PATH"/robots.txt "$BASE_PATH"/releases/"$NEW_RELEASE"/robots.txt

# Set storage path
rm -rf "$BASE_PATH"/releases/"$NEW_RELEASE"/storage
ln -s "$BASE_PATH"/storage "$BASE_PATH"/releases/"$NEW_RELEASE"/storage


# Go to the new release and run all the necessary commands
cd "$BASE_PATH"/releases/"$NEW_RELEASE" || exit 1

php artisan migrate --force

# Composer install
if [ $ENVIRONMENT == 'production' ]; then
    composer install --no-interaction --no-dev --prefer-dist --optimize-autoloader  || exit 1
else
    composer install  || exit 1
fi

echo "Trigger deploy"
# Secondary migrations from package changes
php artisan deploy  || exit 1

#php artisan storage:link
php artisan config:cache || exit 1
php artisan route:cache || exit 1
php artisan event:cache || exit 1
#php artisan cache:clear


# Go back home
echo "Relink files"
cd "$BASE_PATH" || exit 1

# remove current symlink
unlink "$BASE_PATH"/public_html
unlink "$BASE_PATH"/current-build

# Create symlink to latest release
ln -s "$BASE_PATH"/releases/"$NEW_RELEASE"/public/ "$BASE_PATH"/public_html
ln -s "$BASE_PATH"/releases/"$NEW_RELEASE" "$BASE_PATH"/current-build

echo "Enable opcache"
sh clearopcache_enable.sh || exit 1

# Go back to release
cd "$CURRENT_DIR" || exit 1

echo "Restart queues"
# send queue restart signal to make sure workers use the new code
php artisan queue:restart

echo "Clean up old versions"
# Drop old build processes
php drop_old_builds.php $NEW_RELEASE
