# Separate wrapper arguments from WP-CLI arguments
WP_CLI_ARGS=()
while[[$# -gt 0]];do
case"$1" in
-h|--help)
usage
;;
--wproot=*)
WP_ROOT="${1#*=}"
shift
;;
--webuser=*)
WEB_USER="${1#*=}"
shift
;;
*)
# Collect all other arguments for WP-CLI
WP_CLI_ARGS+=("$1")
shift
;;
esac
done
# Check for mandatory arguments
if[[${#WP_CLI_ARGS[@]} -lt 2]];then
error_exit "Missing required <search> and <replace> arguments."
fi
info "Wrapper settings: WP_ROOT='${WP_ROOT}', WEB_USER='${WEB_USER}'"
info "Arguments passed to WP-CLI: ${WP_CLI_ARGS[*]}"
# --- Prerequisite Checks ---
info "Checking prerequisites..."
if[[ ! -d "$WP_ROOT"]];then error_exit "WordPress root directory '$WP_ROOT' does not exist.";fi
if ! command -v "$WP_CLI_PATH"&> /dev/null;then
warning "WP-CLI not found at $WP_CLI_PATH."
if ! command -v "wp"&> /dev/null;then
error_exit "WP-CLI not found at $WP_CLI_PATH or in system PATH. Please install WP-CLI."
else
WP_CLI_PATH="wp"# Fallback to wp in path
info "Found 'wp' in system PATH. Using that."
fi
fi
if ! id "$WEB_USER"&>/dev/null;then error_exit "Web user '$WEB_USER' does not exist.";fi
success "Prerequisites seem OK."
# --- WP-CLI Execution Context Setup ---
# This logic is adapted from install-wordpress.sh to ensure commands run as the correct user.
WP_RUN_ARGS=("--path=$WP_ROOT")
SUDO_CMD=""
WP_EXECUTABLE="$WP_CLI_PATH"
if[["$(id -u)" -eq 0]];then
info "Script is running as root. Attempting to run WP-CLI as '$WEB_USER'."
# Use 'sudo -n' to check for passwordless sudo access.
if sudo -n -u "$WEB_USER""$WP_EXECUTABLE" --info --skip-update --quiet "${WP_RUN_ARGS[@]}"&>/dev/null;then
SUDO_CMD="sudo -u $WEB_USER"
info "WP-CLI will be executed as '$WEB_USER'."
else
warning "Could not execute WP-CLI as '$WEB_USER' without a password. Falling back to running as root."
WP_RUN_ARGS+=("--allow-root")
fi
else
if[["$(id -un)" !="$WEB_USER"]];then
info "Script is running as non-root user '$(id -un)'. Checking for sudo access to run as '$WEB_USER'."
if sudo -n -u "$WEB_USER""$WP_EXECUTABLE" --info --skip-update --quiet "${WP_RUN_ARGS[@]}"&>/dev/null;then
SUDO_CMD="sudo -u $WEB_USER"
info "Successfully configured sudo execution for WP-CLI as '$WEB_USER'."
else
error_exit "Unable to execute WP-CLI as '$WEB_USER'. Ensure the current user has passwordless sudo access, or run this script as '$WEB_USER' or 'root'."
fi
else
info "Script is already running as the web user ('$WEB_USER')."
fi
fi
info "WP-CLI final execution command prefix: [${SUDO_CMD:-direct}]"
# --- Execute Command ---
info "Executing 'wp search-replace'..."
# Build command array safely to preserve argument quoting
CMD=()
if[[ -n "$SUDO_CMD"]];then
# shellcheck disable=SC2206
CMD=($SUDO_CMD)# split sudo command into array elements