#!/usr/bin/env bash
# bin/compile <build-dir>

# fail hard
set -o pipefail
# fail harder
set -eu

BUILD_DIR=${1:-}
CACHE_DIR=${2:-}
ENV_DIR=${3:-}
BP_DIR=$(cd "$(dirname "${0:-}")"; cd ..; pwd)

# convenience functions
source "$(cd $(dirname $0); pwd)"/util.sh

create_default_env "$BUILD_DIR" "$CACHE_DIR"
export_env_dir "$ENV_DIR"

status "Installing WP-CLI..."

download_wpcli $BUILD_DIR/.heroku/wp-cli/bin/wp

chmod +x $BUILD_DIR/.heroku/wp-cli/bin/wp

mkdir -p $BUILD_DIR/.profile.d

echo "export PATH=\"\$PATH:\$HOME/.heroku/wp-cli/bin\"" > $BUILD_DIR/.profile.d/100-wpcli.sh

wp() {
	$BUILD_DIR/.heroku/wp-cli/bin/wp "$@" | indent
}

export -f wp

# Use 'wp-cli.heroku.yml' file if exists, otherwise fallback to 'wp-cli.yml'
if [ -f $BUILD_DIR/wp-cli.heroku.yml ]; then
    wpcli_yml=$BUILD_DIR/wp-cli.heroku.yml
else
    wpcli_yml=$BUILD_DIR/wp-cli.yml
fi

if [ ! -f $wpcli_yml ]; then
error <<-EOF
    Failed to configure WP-CLI!

    File 'wp-cli.yml' is required during this process.
EOF
fi

cd $BUILD_DIR

# We can't validate wp-cli.yml content right now
# So, I assumed that the 'url' config is exists
# but with different address, let say: `url: http://localhost`
cp $wpcli_yml $BUILD_DIR/wp-cli.local.yml

if [ -z $WP_HOME ]; then
    export WP_HOME="http://${HEROKU_APP_NAME}.herokuapp.com"
fi

sed -i -E "s~url: .*~url: ${WP_HOME}~" $BUILD_DIR/wp-cli.local.yml

# I think we should add custom envvar to configure these flags
# But I'll leave it as it for now.
if wp core is-installed; then
    status 'WordPress is installed'
    wp cache flush
else
    if [ ! -z $MULTISITE ] && [ "${MULTISITE}" -eq "true" ]; then
        status 'Installling WordPress Multisite'
        wp core multisite-install --skip-email --title="WordPress Local" \
            --admin_user="admin" --admin_password="secret" --admin_email="demo@example.com"
    else
        status 'Installling WordPress'
        wp core install --skip-email --title="WordPress Local" \
            --admin_user="admin" --admin_password="secret" --admin_email="demo@example.com"
    fi
fi

status "Setup completed"
