#!/bin/bash

# Script for deploying any updated JS and/or styles
#
# - Build and minify all of the apps under js/apps
# - For each app:
#   - If the new minified file is different from the last deployed production release
#       - Remove old production releases
#       - Create and commit a new production release
#   - Build styles and commit the built CSS file (if different from the current version in the repo)

fail() {
    local status=$?;
    local description=$1;
    echo "ERROR: ${description} failed with status ${status}" >&2;
    exit -1;
}

git config --global --add safe.directory /var/www/html

gulp build-all || fail 'build-all';
gulp min-all || fail 'min-all';

for app_file in ./js/apps/*.js; do
    must_deploy=false;
    app_name=$(basename "$app_file" .js);
    new_min_path="../public/js/dev/${app_name}.min.js";
    last_deployed=$(ls ../public/js/releases/${app_name}-[0-9]*.min.js 2>/dev/null | tail -n 1);

    if [ -z "${last_deployed}" ]; then
        must_deploy=true;
    else
        diff "$new_min_path" "$last_deployed" > /dev/null;
        if [ $? -ne 0 ]; then
            must_deploy=true;
        fi
    fi

    if $must_deploy; then
        echo "Deploying ${app_name}...";
        if [ -n "${last_deployed}" ]; then
            # clean up the existing deployed files before re-deploying
            git rm ../public/js/releases/${app_name}-[0-9]*.min.js;
        fi
        gulp deploy-only --app_name="$app_name" || fail "${app_name} deploy-only";
        git add "../public/js/releases/${app_name}-[0-9]*.min.js" "../public/js/dev/${app_name}.js" "../public/js/dev/${app_name}.min.js";
    else
        git checkout "../public/js/dev/${app_name}.js";
    fi
done

for app_file in ./style-redesign/applications/*-redesign.scss; do
    app_name=$(basename "$app_file" -redesign.scss);
    gulp --app="$app_name" style-build-redesign || fail "${app_name} style-build-redesign";
done

for app_file in ./style-redesign/oa-applications/*-redesign.scss; do
    app_name=$(basename "$app_file" -redesign.scss);
    gulp --app="$app_name" style-build-redesign || fail "${app_name} style-build-redesign";
done

git add ../public/css;
# Return 0 even if git commit returned non-zero. That happens if there are no changes to commit.
exit 0;
