package Cpanel::Easy::Utils::RPM;

# cpanel - Cpanel/Easy/Utils/RPM.pm               Copyright(c) 2014 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cpanel license. Unauthorized copying is prohibited

use strict;
use warnings;

# Hash of all targets currently supported by EasyApache;
# should match the target list in easy.versions.
# Add to this as new targets are added to EA.
my %rpm_targets = (
    'easy-tomcat7' => 0,
);

our $check_cpanel_rpms         = '/usr/local/cpanel/scripts/check_cpanel_rpms';
our $update_local_rpm_versions = '/usr/local/cpanel/scripts/update_local_rpm_versions';

# Update all RPMs for currently selected targets
sub process_rpms {
    my ($self) = @_;
    $self->print_alert_color( 'blue', q{Processing RPMs...} );

    my $profile = $self->{'working_profile'};
    for my $ns ( sort keys %$profile ) {
        next unless $ns =~ /^Cpanel::Easy::/;
        next unless $profile->{$ns};
        eval qq{ require $ns; };
        my $ec = $self->get_easyconfig_hr_from_ns_via_state($ns);
        if ( $ec && $ec->{'easy-rpms'} ) {
            for my $target ( @{ $ec->{'easy-rpms'} } ) {
                $rpm_targets{$target} = $ec->{'skip'} ? 0 : 1;    # Case 163713
            }
        }
    }

    # Update the local.versions file with the currently selected targets
    my @targets = sort keys %rpm_targets;
    for my $target ( sort keys %rpm_targets ) {
        my ( $status, $output ) = $self->update_local_rpm_versions( $target, $rpm_targets{$target} );
        if ( !$status ) {
            return ( $status, $output );
        }
    }

    my ( $status, $output ) = $self->check_cpanel_rpms(@targets);
    if ( !$status ) {
        return ( $status, $output );
    }
    $self->print_alert($output) if $output;
    return ( 1, 'ok' );
}

# Update the 'installed' status of a target in the local.versions file
sub update_local_rpm_versions {
    my ( $self, $target, $installed ) = @_;
    my $arg = $installed ? 'installed' : 'uninstalled';

    my $output = Cpanel::SafeRun::saferunallerrors(
        $update_local_rpm_versions, '--edit', "target_settings.$target",
        $arg
    );

    $self->print_alert( "[_1] will be [_2]", $target, $arg );

    return ( !( $? >> 8 ), $output );
}

# Install/uninstall RPMs as needed
sub check_cpanel_rpms {
    my ( $self, @targets ) = @_;

    # If there are no targets, do nothing
    return ( 1, 'ok' ) unless @targets;

    my $targets = join( ',', @targets );
    my $output = Cpanel::SafeRun::saferunallerrors( $check_cpanel_rpms, '--fix', "--targets=$targets" );
    return ( !( $? >> 8 ), $output );
}

1;
