#!/bin/bash
#######################################
# WP_CLI_VERSION=v2.12.0
# Timed-out wrapper around wp-cli
# Arguments:
#   $1 - Path to PHP binary, full filesystem path
#   $2 - Path to Wordpress installation, full filesystem path
#   $3 - Optional --force-theme-load: run with the active theme loaded
#   All the rest arguments ($@) are treated as WP-CLI command
# Environment:
#   WP_CLI_WRAPPER_PHAR    - WP-CLI phar to run, default /usr/share/imunify360/wp-plugins/wp-cli
#   WP_CLI_WRAPPER_TIMEOUT - limit for every PHP run, as for timeout(1), default 2m; 0 means no limit
#   WP_CLI_WRAPPER_RETRY   - 0 turns off the retry (see Modes); any other value keeps it on
# Modes:
#   default            - WP-CLI runs with --skip-themes, because many themes break under WP-CLI.
#                        A run that fails with an exit code other than 0 or 1 is run once more
#                        without --skip-themes.
#   single run         - WP_CLI_WRAPPER_RETRY=0, or stdin is a pipe or a file: one run with
#                        --skip-themes and no retry. A second run of a command that read its
#                        stdin would get an empty one, so a caller that passes stdin=PIPE loses
#                        the retry.
#   --force-theme-load - one run with the theme loaded and no retry, whatever
#                        WP_CLI_WRAPPER_RETRY says. Standard input goes to WP-CLI as is (the
#                        caller may send secrets this way, so it is never logged). The caller
#                        decides what to do after a failure.
#   Every mode uses the timeout and the environment below.
# Outputs:
#   Writes WP-CLI's stdout, trailing newlines included, whether or not the command was retried
# Exit status:
#   WP-CLI's, or 69 when the wrapper itself cannot run it (no PHP version, no WordPress directory);
#   the wrapper's own errors are never retried
# WP-CLI runs without a global config, packages, cache or update check, but still reads wp-cli.yml and
# wp-cli.local.yml from the WordPress directory and its parents.
#######################################
PATH_TO_PHP="$1"
PATH_TO_WP="$2"

shift 2

FORCE_THEME_LOAD=0
if [[ "$1" == "--force-theme-load" ]]; then
  FORCE_THEME_LOAD=1
  shift
fi

WP_CLI="${WP_CLI_WRAPPER_PHAR:-/usr/share/imunify360/wp-plugins/wp-cli}"

TIMEOUT="${WP_CLI_WRAPPER_TIMEOUT:-2m}"
# without -k a PHP that ignores SIGTERM outlives the limit
KILL_AFTER="10s"

RETRY="${WP_CLI_WRAPPER_RETRY:-1}"
# a second run of a command that read its stdin (a key on a pipe) would get an empty one
if [ -p /dev/stdin ] || [ -f /dev/stdin ]; then
  RETRY=0
fi

# a global WP-CLI config can `require:` PHP files (wp-cli.yml in the docroot is still read);
# packages, cache and the update check are not needed. /dev/null cannot become a directory, while
# /nonexistent is created when the wrapper runs as root.
export WP_CLI_DISABLE_AUTO_CHECK_UPDATE=1
export WP_CLI_CONFIG_PATH=/dev/null
export WP_CLI_PACKAGES_DIR=/nonexistent/wp-cli-packages
export WP_CLI_CACHE_DIR=/dev/null

LIMIT=()
if [ "$TIMEOUT" != "0" ]; then
  LIMIT=(timeout -k "$KILL_AFTER" "$TIMEOUT")
fi

# -n: without php.ini no startup warning can precede the number
PHP_VERSION_ID=$("${LIMIT[@]}" "$PATH_TO_PHP" -n -d display_errors=0 -r 'echo PHP_VERSION_ID;' 2>/dev/null)

case "$PHP_VERSION_ID" in
  ''|*[!0-9]*)
    echo "Error: failed to determine PHP version from '$PATH_TO_PHP' (the version probe timed out or returned no parseable version)" >&2
    exit 69
    ;;
esac

PHP_DEFAULT_EXTENSIONS=(phar)

# PHP 8.0 and above have json extension enabled by default
if (( PHP_VERSION_ID < 80000 )); then
  PHP_DEFAULT_EXTENSIONS+=(json)
fi

# for PHP 8.2 and above mysqlnd must be loaded before mysqli
if (( PHP_VERSION_ID >= 80200 )); then
  PHP_DEFAULT_EXTENSIONS+=(mysqlnd)
fi

PHP_DEFAULT_EXTENSIONS+=(mysqli)

PHP_EXTRA_OPTIONS=(-d memory_limit=-1 -d open_basedir=none)

# explicitly drop PHP disable_functions directive in order to avoid errors like
# 'Error: Cannot do 'launch': The PHP functions `proc_open()` and/or `proc_close()` are disabled'
# during plugin manipulations
PHP_DEFAULT_FUNCTIONS=(-d disable_functions= -d display_errors=0 -d error_log=/dev/null)

# Defaults for WP-CLI
WP_CLI_DEFAULT_OPTS=("--skip-themes") # Must be first [0]
WP_CLI_DEFAULT_OPTS+=("--skip-packages")

# Define constants
WP_CLI_DEFAULT_OPTS+=("--exec=define('WP_DEBUG', true);")
WP_CLI_DEFAULT_OPTS+=("--exec=define('WP_DEBUG_DISPLAY', false);")
WP_CLI_DEFAULT_OPTS+=("--exec=define('DISABLE_WP_CRON', true);")

# Construct PHP extensions to include; whole names only, "json" must not match "jsond"
LOADED_EXTENSIONS=$("${LIMIT[@]}" "$PATH_TO_PHP" -d display_errors=0 -m 2>/dev/null)
EXTS=()
for ext in "${PHP_DEFAULT_EXTENSIONS[@]}"
do
  if ! printf '%s\n' "$LOADED_EXTENSIONS" | grep -qix -- "$ext"; then
    EXTS+=(-d "extension=$ext.so")
  fi
done

# change current working directory
# we need this because if php code has relative imports
# it looks for scripts inside current directory first
# e.g. some providers add require('wp-salt.php') to config
# https://stackoverflow.com/questions/75823716/
# the overall approach of relative import is not correct,
# but we still need patch for this
cd "${PATH_TO_WP}" || exit 69

if (( FORCE_THEME_LOAD )); then
  # Index [0] is --skip-themes. No retry: standard input is read once.
  exec "${LIMIT[@]}" \
    "$PATH_TO_PHP" "${EXTS[@]}" "${PHP_EXTRA_OPTIONS[@]}" "${PHP_DEFAULT_FUNCTIONS[@]}" \
    "$WP_CLI" --path="$PATH_TO_WP" "${WP_CLI_DEFAULT_OPTS[@]:1}" "$@"
fi

if [ "$RETRY" = "0" ]; then
  exec "${LIMIT[@]}" \
    "$PATH_TO_PHP" "${EXTS[@]}" "${PHP_EXTRA_OPTIONS[@]}" "${PHP_DEFAULT_FUNCTIONS[@]}" \
    "$WP_CLI" --path="$PATH_TO_WP" "${WP_CLI_DEFAULT_OPTS[@]}" "$@"
fi

# The dot keeps the trailing newlines that $(...) would strip, so the output matches the exec path above.
run_wp_cli() {
  WP_CLI_RESULT=$("${LIMIT[@]}" \
               "$PATH_TO_PHP" "${EXTS[@]}" "${PHP_EXTRA_OPTIONS[@]}" "${PHP_DEFAULT_FUNCTIONS[@]}" \
               "$WP_CLI" --path="$PATH_TO_WP" "${WP_CLI_DEFAULT_OPTS[@]}" "$@"
               code=$?; printf .; exit $code)
  WP_CLI_CODE=$?
  WP_CLI_RESULT=${WP_CLI_RESULT%.}
}

run_wp_cli "$@"

# Not 0 and not 1 because WP-CLI has commands that return status as the result of the command execution
# For example plugin is-active, exit status 0 if active, otherwise 1
# Calling an error at the php level will return 255
# Let's try to run the command without --skip-themes
if [ "$WP_CLI_CODE" -ne 0 ] && [ "$WP_CLI_CODE" -ne 1 ]; then
  echo "Retry without --skip-themes" >&2
  unset 'WP_CLI_DEFAULT_OPTS[0]'

  run_wp_cli "$@"
fi

printf '%s' "$WP_CLI_RESULT"
exit $WP_CLI_CODE
