
#                                      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 Common::Plugins::Setup;

=encoding utf8

=head1 NAME

Common::Plugins::Setup

=head1 DESCRIPTION

Setup related functionality for plugins.

=cut

use cPstrict;
use Cpanel::Exception        ();
use Common::Plugins::LoadRun ();

# TODO DUCKS-1513 Automatic method of registering plugins for this plugin/dirname table.
# Until this is accomplished, manual update of this is required for each new plugin that
# wants to expose enable/disable functionality.
our %PLUGIN_DIRS = (
    'cpanel-monitoring-plugin' => '360Monitoring',
);

=head1 FUNCTIONS

=cut

=head2 run_from_module()

This function finds a module, loads it, and runs an input command on it.

Initially, only disable or enable are allowed, functions that allow an
admin to bypass certain checks to enable/disable plugins.

=head3 ARGUMENTS

=over

=item app_name - string

Required. Either 'Cpanel' or 'Whostmrg' - whichever cPanel app the plugin needing this lives in.

=item plugin_name - string

Required. The plugin name that matches the package-advertised plugin name.

=item function_to_run - string

Required. Functions like 'enable' or 'disable' that the plugin can run.

=back

=cut

sub run_from_module ( $app_name, $plugin_name, $function_to_run ) {
    my $dir_name = _get_dir_name($plugin_name)
      or die Cpanel::Exception::create( 'InvalidParameter', "The plugin $plugin_name was not found, or it is not able to $function_to_run by API" );

    my $module = "${app_name}::${dir_name}::Setup";

    _validate_fn_name($function_to_run);

    my $method = $module . "::" . "local_" . $function_to_run;

    # execute the enable or disable sub
    return Common::Plugins::LoadRun::run_from_module( $module, $method );
}

sub _get_dir_name ($plugin_name) {

    my $dir_name = $PLUGIN_DIRS{$plugin_name};

    return $dir_name;
}

sub _validate_fn_name ($function_to_run) {
    my $allowed_fns = qr/^(enable|disable)$/;
    $function_to_run =~ $allowed_fns
      or die Cpanel::Exception::create( 'InvalidParameter', "The function $function_to_run is not allowed to run by API" );
    return 1;
}

1;
