#!/usr/bin/perl
# cpanel - autofixer2/ea3_tomcat_stackmemory_start_option
#                                                    Copyright 2017 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;
use Cpanel::SafeFile ();
use IO::Handle       ();
use Cpanel::LoadFile ();

my $restart = 1;

if ( !-x '/usr/sbin/starttomcat' ) {
    print "INFO: tomcat not installed\n";
    $restart = 0;
}

if ( -e '/etc/tomcatdisable' ) {
    print "INFO: tomcat is disabled\n";
    $restart = 0;
}

my $tomcatopts = Cpanel::LoadFile::load_if_exists('/var/cpanel/tomcat.options') || '';
$tomcatopts =~ s/^\s*$//g;

if ( !$tomcatopts || $tomcatopts =~ s/^\-Xss[0-3]m$/-Xss4m/m ) {

    print "Adding -Xss4m to tomcat.options …\n";

    my $fh = IO::Handle->new();
    my $lock = Cpanel::SafeFile::safeopen( $fh, '>', '/var/cpanel/tomcat.options' );
    if ($lock) {
        print {$fh} $tomcatopts || "-Xss4m\n";
        Cpanel::SafeFile::safeclose( $fh, $lock );
        exec("/usr/local/cpanel/scripts/restartsrv_tomcat") if $restart;
    }
    else {
        print "Failed to lock /var/cpanel/tomcat.options: -Xss4m will need manaully added\n";
        exit(1);
    }
}
else {
    print "Nothing to do: tomcat.options already has a valid Xss setting.\n";
}

exit(0);
