#                                     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 Cpanel::Plugins::Components::Rules::CpanelVersion;
use cPstrict;

use Cpanel::Version;
use Cpanel::Version::Compare;

use Moo;
extends 'Cpanel::Plugins::Components::Rules::Base';

=head1 MODULE

C<Cpanel::Plugins::Components::Rules::CpanelVersion>

=head1 DESCRIPTION

Evaluates if the current server has a specific cPanel Version.

This class is used if the campaign config file has 'cpanel-version' listed.

C<Cpanel::Plugins::Components::Rules::CpanelVersion> provides

=head1 SYNOPSIS

Check if the server has a cPanel version 110

  use Cpanel::Plugins::Components::Rules::CpanelVersion;
  my $return = Cpanel::Plugins::Components::Rules::CpanelVersion->new('11.110')->is_allowed();

When you are using the declaritive JSON syntax:

  {
    "cpanelversion": "11.110"
  }

=cut

=head1 METHODS

=over

=item * is_allowed -- Allow the campaign if rules are met.

    RETURNS
        0 - The cPanel version check failed.
        1 - The cPanel version check succeeded.

    ERRORS
        Fails if no cPanel version is passed.
        Fails if unable to fetch the cPanel version.

=back

=cut

around BUILDARGS => sub {
    my ( $orig, $class, @args ) = @_;

    # ( 1 )
    return { config => [ $args[0] ] }
      if @args == 1 && !ref $args[0];

    # ( [ 1 ] )
    return { config => $args[0] }
      if @args == 1 && ref $args[0];

    # ( config => 1 ) ... ( config => [1] )
    my %args = @args;
    $args{config} = [ $args{config} ] if !ref $args{config};
    return $class->$orig(%args);
};

sub is_allowed ($self) {
    my $cp_version_ref = $self->config;

    # Validate the config passed
    die "You must provide one or more cPanel version data."
      if !defined $cp_version_ref || ref $cp_version_ref ne 'ARRAY';

    my $version = Cpanel::Version::getversionnumber();
    foreach my $cp_version (@$cp_version_ref) {

        #TODO: expand this rule to include operators
        my $operator = '==';

        # for now, we can restrict this in rules to specify the exact
        # two part version
        if ( $cp_version !~ /^(\d){2}\.(\d){3}$/ ) {
            die "You must provide a two part cPanel version like 'xx.xxx'";
        }

        if ( Cpanel::Version::Compare::compare_major_release( $version, $operator, $cp_version ) ) {
            return !!1;
        }

    }
    return !!0;

}

1;
