#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - scripts/wordpresss_use_best_php         Copyright 2019 cPanel, L.L.C.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

package scripts::wordpress_use_best_php;

use strict;
use warnings;

use lib "/usr/local/cpanel/cpaddons/";

use cPanel::Blogs::WordPressX::BestPHP ();    # provided by this cpaddon
use Cpanel::API::DomainInfo            ();
use Cpanel::API::LangPHP               ();
use Cpanel::Args                       ();
use Cpanel::JSON                       ();
use Cpanel::Result                     ();
use Cpanel::SafeRun::Errors            ();
use Getopt::Long                       ();
use Pod::Usage                         ();

# we don't care about the feature check since we are
# just trying to reuse the same .htaccess writer, not
# giving the user a generalized accesss.
local *main::hasfeature = sub { return 1; };

exit( __PACKAGE__->run(@ARGV) ) if !caller;

=head1 DESCRIPTION

This script checks the installed php versions looking for the compatible php
that includes the dependencies that WordPress needs to install and run. If a
compatible version of php is found, but it does not have all the required
dependencies available, it is skipped. If a compatible version of php is
not found the script dies.

The highest version of php that matches all the prerequistes is selected. If the
site does not currently use this version of php, the site is updated to use it.

=head1 USAGE

wordpress_use_best_php --domain={string}

Where:

=over

=item * --domain={string} - The domain name for which to set the the default php version.

=item * --verbose - Output verbose messages.

=item * --help - Output this help.

=item * --man  - Output the full man page.

=back

=cut

sub run {
    my ( $self, @args ) = @_;
    my ( $help, $man, $domain, $verbose ) = ( 0, 0, '', 0 );

    Getopt::Long::GetOptionsFromArray(
        \@args,
        'help|?'    => \$help,
        'man'       => \$man,
        'verbose|v' => \$verbose,
        'domain=s'  => \$domain,
    ) or Pod::Usage::pod2usage(2);
    Pod::Usage::pod2usage(1) if $help;
    Pod::Usage::pod2usage( -exitval => 0, -verbose => 2 ) if $man;

    if ( !defined $domain || $domain eq '' ) {
        die 'You must pass a --domain value';
    }

    # Remove leading/trailing whitespace
    $domain =~ s/^\s+|\s+$//g;

    my $best_php = cPanel::Blogs::WordPressX::BestPHP::get_best_php( verbose => $verbose );
    if ( !$best_php ) {
        die "Could not find a version of php installed that has all the required extensions installed.";
    }

    local $Cpanel::user = ( getpwuid( int($<) ) )[0];
    my $vhost = $domain;

    my $domain_info_res = Cpanel::Result->new();
    if ( !Cpanel::API::DomainInfo::list_domains( Cpanel::Args->new(), $domain_info_res ) ) {
        die "Can not set the php version since we can not lookup the domain information with error: " . $domain_info_res->error_as_string();
    }

    my $domain_info    = $domain_info_res->data();
    my $parked_domains = $domain_info->{parked_domains};
    if ( $parked_domains && ref $parked_domains eq 'ARRAY' && grep { $_ eq $domain } @$parked_domains ) {
        $vhost = $domain_info->{main_domain};
    }

    my $vhost_res = Cpanel::Result->new();
    if ( !Cpanel::API::LangPHP::php_get_vhost_versions( Cpanel::Args->new(), $vhost_res ) ) {
        die "Can not set the php version since we can not lookup php vhost information with error: " . $vhost_res->error_as_string();
    }

    my $config;
    foreach ( @{ $vhost_res->data() } ) {
        if ( $vhost eq $_->{vhost} ) {
            $config = $_;
            last;
        }
    }

    if ( !$config ) {
        die "The requested domain, $domain, does not exist on this account.";
    }

    if ( $config->{version} ne $best_php ) {

        print "Updating the site at $domain to use $best_php\n" if $verbose;

        my $json = Cpanel::SafeRun::Errors::saferunallerrors(
            '/usr/local/cpanel/bin/uapi',
            '--output', 'json',
            'LangPHP', 'php_set_vhost_versions',
            'vhost', $vhost,
            'version', $best_php);
        my $response = Cpanel::JSON::Load($json);

        if ( !$response->{result}{status} ) {
            my $error = join(' ', @{ $response->{result}{errors} });
            die $error if $error;
            die "Unknown error.";
        }

        print "Success\n" if $verbose;
    }

    return 0;
}

1;
