#!/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:-}
BIN_DIR=$(cd $(dirname $0); pwd)
BP_DIR=$(cd "$(dirname "${0:-}")"; cd ..; pwd)

# convenience functions
source "$BIN_DIR"/util.sh

mkdir -p "$BUILD_DIR/.heroku/wp-cli/bin"

# if the build dir is not "/app", we symlink in the .heroku/wp-cli subdir
# (and only that, to avoid problems with other buildpacks) so that PHP correctly finds its INI files etc
[[ $BUILD_DIR == '/app' ]] || ln -s $BUILD_DIR/.heroku/wp-cli /app/.heroku/wp-cli

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!

    This is most likely a temporary internal error. If the problem
    persists, make sure that you are not running a custom or forked
    version of the Heroku Ruby buildpack which may need updating.
EOF
}

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
sed -i -E "s~url: .*~url: ${WP_HOME}~" $BUILD_DIR/wp-cli.local.yml

status "Installing WordPress"

# I think we should add custom envvar to configure these flags
# But I'll leave it as it for now.
wp core install --skip-email --title="WordPress Site" --admin_user="admin" --admin_password="secret" --admin_email="demo@example.com"

status "Setup completed"
