#                                      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 Whostmgr::360Monitoring::LifeCycle;

=encoding utf8

=head1 NAME

Whostmgr::360Monitoring::LifeCycle

=head1 DESCRIPTION

LifeCycle related functionality for cpanel-monitoring-plugin.

=cut

use cPstrict;
use Common::Plugins::Setup::Steps ();
use Cpanel::Exception             ();
use Cpanel::Imports;

my $APP_NAME   = 'Server Monitoring (Powered by 360 Monitoring)';
my $PLUGIN_DIR = '/var/cpanel/plugins/monitoring';

my %INSTALL_STEPS = (
    "/usr/local/cpanel/scripts/initialize_360monitoring" => {
        args    => [],
        message => "Setting up the $APP_NAME plugin"
    },
);

my %UNINSTALL_STEPS = (
    "$PLUGIN_DIR/uninstall.sh" => {
        args    => [],
        message => "Uninstalling the $APP_NAME plugin"
    },
    "/usr/local/cpanel/bin/manage_hooks" => {
        args    => [ 'delete', 'module', 'Whostmgr::360Monitoring::Hooks::ServerRoleChange' ],
        message => "Removing the hooks for ServerRoleChange"
    },
);

=head2 is_setup_already()

Check if the plugin is already setup. May not be needed on all plugins.

=head3 RETURNS

1 if the plugin is already setup, 0 otherwise.

=cut

sub is_setup_already() {
    require Whostmgr::360Monitoring::Setup;
    return Whostmgr::360Monitoring::Setup::is_setup();
}

=head2 install()

Run the installation steps for the plugin.

=head3 RETURNS

1 if successful. Otherwise, throws an exception.

=head3 THROWS

=over

=item Various failure messages.

=back

=cut

sub install () {

    return if is_setup_already();

    my ( $success, $failures ) = Common::Plugins::Setup::Steps::run_steps( $APP_NAME, %INSTALL_STEPS );

    if ($success) {
        return 1;
    }

    if ( $failures && @$failures < keys %INSTALL_STEPS ) {
        die Cpanel::Exception->create( "Some of the steps used to install $APP_NAME failed: " . join( "\n", @$failures ) );
    }
    die Cpanel::Exception->create( "Failed to install $APP_NAME: " . join( "\n", @$failures ) );
}

=head2 uninstall()

Run the removal steps for the plugin.

=head3 RETURNS

1 if successful. Otherwise, throws an exception.

=head3 THROWS

=over

=item Various failure messages.

=back

=cut

sub uninstall () {

    my ( $success, $failures ) = Common::Plugins::Setup::Steps::run_steps( $APP_NAME, %UNINSTALL_STEPS );

    if ($success) {
        return 1;
    }

    if ( $failures && @$failures < keys %UNINSTALL_STEPS ) {
        die Cpanel::Exception->create( "Some of the steps used to uninstall $APP_NAME failed: " . join( "\n", @$failures ) );
    }
    die Cpanel::Exception->create( "Failed to uninstall $APP_NAME: " . join( "\n", @$failures ) );
}

1;
