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

package autofixer2::mysqlconfopenfileslimit;
use strict;

BEGIN {
    unshift @INC, '/usr/local/cpanel';
}

our $VERSION = '1.1';

# remove open_file_limit with something else and and a new line at the end

fix() unless caller();

sub _mysqldisable {
    return '/etc/mysqldisable';
}

sub _my_cnf {
    return '/etc/my.cnf';
}

sub fix {
    return if -e _mysqldisable();
    my $my_cnf = _my_cnf();
    return unless -e $my_cnf;

    my $need_update;
    my $fh;
    if ( open( $fh, '+<', $my_cnf ) ) {
        my @keep;
        my $has_open_files_limit;
        my $count_open_files = 0;
        while ( my $line = <$fh> ) {
            if ( $line !~ /^\s*#/ && $line =~ /open_files_limit/ ) {
                ++$count_open_files;
                my ( $previous_line, $trash ) = split( 'open_files_limit', $line, 2 );
                if ($previous_line) {
                    push @keep, $previous_line . "\n";
                    $need_update = 1;
                }
                elsif ( !$has_open_files_limit ) {
                    push @keep, $line;
                    $has_open_files_limit = 1;
                    $need_update          = 1;
                }
                next;
            }

            # by default keep the line
            push @keep, $line;

        }

        # do not need to update if contain only one single valid open_files_limit entry
        $need_update = 0 if $has_open_files_limit && $count_open_files == 1;

        if ( scalar @keep ) {
            my $last_line = $keep[-1];
            chomp($last_line);
            if ( $last_line eq $keep[-1] ) {
                $keep[-1] .= "\n";
                $need_update = 1;
            }
        }
        if ($need_update) {
            seek( $fh, 0, 0 );
            foreach my $line (@keep) {
                print $fh $line;
            }
            truncate( $fh, tell($fh) );
        }
        close($fh);
    }
    return $need_update;
}

1;
