#!/usr/local/cpanel/3rdparty/bin/perl
# cpanel - autofixer2/fix_imagick_pecl            Copyright(c) 2015 cPanel, Inc.
#                                                           All rights Reserved.
# copyright@cpanel.net                                         http://cpanel.net
# This code is subject to the cPanel license. Unauthorized copying is prohibited

# Required for legacy machines.
BEGIN { unshift @INC, '/usr/local/cpanel'; }

use strict;
use warnings;

use Cpanel::SafeFile      ();
use Cpanel::Version::Tiny ();

my $module = 'imagick';

exit script() unless caller;

sub script {
    return 0 unless wanted();
    return reinstall_pecl();
}

sub wanted {
    local $ENV{'LC_ALL'} = 'C';
    return if $Cpanel::Version::Tiny::VERSION =~ /^11\.(\d+)/ && $1 < 36;
    my $lock = Cpanel::SafeFile::safeopen( my $fh, '<', '/usr/local/lib/php.ini' );
    my $has_pecl_module;
    if ($lock) {
        while (<$fh>) {
            if (/^extension="?\Q$module\E\.so"?/) {
                $has_pecl_module = 1;
                last;
            }
        }
        Cpanel::SafeFile::safeclose( $fh, $lock );
    }
    return unless $has_pecl_module;
    return unless -x '/usr/bin/php-cli';

    my $output = `/usr/bin/php-cli --re imagick`;
    return 1 if $output =~ /does not exist/;
    return;
}

sub reinstall_pecl {
    require Cpanel::LangMods;
    print "\n==== Uninstall $module ====\n";
    print Cpanel::LangMods::doaction( "php-pecl", "uninstall", $module );
    print "\n====\n";
    print "\n==== Install $module ====\n";
    print Cpanel::LangMods::doaction( "php-pecl", "install", $module );
    print "\n====\n";
    return 0;
}
