#!/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)

# Configure defaults
WP_HOME=${WP_HOME:-}
HEROKU_APP_NAME=${HEROKU_APP_NAME:-}
MULTISITE=${MULTISITE:-false}

if [ -n "$HEROKU_APP_NAME" ] && [ ! -n "$WP_HOME"]; then
    WP_HOME=https://${HEROKU_APP_NAME}.herokuapp.com
fi

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

mkdir -p "$BUILD_DIR"/.heroku/wp-cli/{bin,cache,packages}

create_default_env "$BUILD_DIR"
export_env_dir "$ENV_DIR"

status "Installing WP-CLI..."

wpcli_url='https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar'

curl_retry --fail --silent --location -o "$BUILD_DIR/.heroku/wp-cli/bin/wp" "$wpcli_url" || {
error <<-EOF
Failed to download a WP-CLI executable for bootstrapping!
EOF
}

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

mkdir -p "$BUILD_DIR/.profile.d"

export WP_HOME

touch $BUILD_DIR/.heroku/wp-cli/config.yml
cat >> $BUILD_DIR/.profile.d/100-wpcli.sh <<EOL
export PATH="\$PATH:\$HOME/.heroku/wp-cli/bin"
export WP_CLI_CACHE_DIR="\$HOME/.heroku/wp-cli/cache"
export WP_CLI_CONFIG_PATH="\$HOME/.heroku/wp-cli/config.yml"
export WP_CLI_PACKAGES_DIR="\$HOME/.heroku/wp-cli/packages"
EOL

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

export -f wp

wpcli_yml="$BUILD_DIR/wp-cli.yml"

# 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"
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"

# 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 already installed'
    wp cache flush
else
    status 'Installling WordPress'
    wp core install --url="$WP_HOME" --skip-email --title="WordPress Local" \
        --admin_user="admin" --admin_password="secret" --admin_email="demo@example.com"
fi

if ! wp core is-installed --network && [ "$MULTISITE" = "true" ]; then
    status 'Installling WordPress Multisite'
    wp core multisite-convert --url="$WP_HOME"
fi

status "Setup completed"
