#!/usr/local/cpanel/3rdparty/bin/perl

#                                      Copyright 2025 WebPros International, LLC
#                                                           All rights reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited.

package bin::wp;

use cPstrict;

use Simple::Accessor qw< slot >;

use Cpanel::PwCache         ();
use Cpanel::SafeRun::Extra  ();
use Cpanel::Security::Authz ();
use Cwd;
use Try::Tiny;

=encoding utf-8

=head1 NAME

bin::wp - A wrapper script for invoking WP-CLI commands

=head1 SYNOPSIS

    wp [command] [options]

=head1 DESCRIPTION

This script serves as a wrapper for invoking WP-CLI commands in a terminal or SSH client environment. WP-CLI is a command-line interface for managing WordPress installations.

=head1 USAGE

Run the script with the desired WP-CLI command and options. For example:

    wp help
    wp plugin list
    wp theme activate twentytwentyone

=head1 SEE ALSO

For more information about WP-CLI, visit the official documentation:

L<https://wp-cli.org/documentation/>

=cut

exit( __PACKAGE__->new()->run(@ARGV) // 0 ) unless caller();

sub run ( $self, @args ) {

    my $status;

    try {
        $status = $self->_run(@args);
    }
    catch {
        my $error = $_;
        if ( ref $error && $error->isa('Cpanel::Exception') ) {
            FATAL( $error->to_locale_string_no_id() );
        }
        else {
            FATAL($error);
        }
    };

    return $status;
}

sub _run ( $self, @args ) {
    Cpanel::Security::Authz::verify_not_root();

    # Here we check that domaindir is part of the current directory
    if ( !$self->_is_user_domain_directory() ) {
        FATAL( <<"EOS" );
Usage: $0

You must to be in the root directory of your website to run this script.
Navigate to your website's root directory and try again.

The root directory is located at ~/public_html/your_domain/
EOS
    }

    # Get response from the WP-CLI callad with actual version of PHP
    $self->run_php_command(
        $self->_wp_binary(),    # use the accurate php version for the website
        @args,                  # pass the arguments to the wp-cli
    );

    return $?;
}

sub FATAL ( $msg = "" ) {
    die "$msg\n";
}

# Check if the script is being run in the user's domain directory
sub _is_user_domain_directory ($self) {

    my $current_dir = Cwd::getcwd();
    my $homedir     = Cpanel::PwCache::gethomedir($>);
    unless ( $homedir && $current_dir ) {
        FATAL("The system could not determine the user's home directory or the current directory in which the script is being executed.");
    }

    my $domaindir = $homedir . '/public_html/';

    # Check if the current directory is part of the domain directory
    # Return -1 if the current directory is not part of the domain directory or 0 if it is
    return index( $current_dir, $domaindir ) != -1;
}

# Get the path to the WP-CLI binary
sub _wp_binary ($self) {

    return q[/usr/local/cpanel/3rdparty/wp-toolkit/plib/vendor/wp-cli/vendor/wp-cli/wp-cli/php/boot-fs.php];
}

# Get the path to the PHP binary
sub _php_binary ($self) {
    return q[/usr/local/bin/php];
}

# Run the PHP command
sub run_php_command ( $self, @args ) {

    my $php_binary = $self->_php_binary();

    my @php_args = (
        '-d' => q[error_reporting='E_ALL&~E_NOTICE&~E_DEPRECATED'],    # Disable deprecated warnings
        '-q'                                                           # Quiet mode (no headers)
    );

    return Cpanel::SafeRun::Extra->new(
        program => $php_binary,
        envs    => {
            'WP_CLI_PHP_USED' => $php_binary,               # Set the PHP binary used
            'WP_CLI_PHP_ARGS' => join( ' ', @php_args ),    # Set the PHP arguments used
            'SHELL_PIPE'      => 1,                         # Enable shell pipe
        },
        args => [
            @php_args,                                      # Pass the PHP arguments
            @args,                                          # Pass the arguments to the wp-cli
        ],
        stdout => \*STDOUT,                                 # Redirect stdout to STDOUT
        stderr => \*STDERR,                                 # Redirect stderr to STDOUT
    );
}

1;
