#!/usr/bin/perl

BEGIN {
   push(@INC,"/scripts");
}

use SafeFile;


if (! -e "/usr/local/jakarta") {
   print "Sorry you must install the cPanel java servlets addon module.";
   exit;
}


$ip = $ARGV[0];
$ip =~ s/\n//g;

$| = 1;

if ($ip eq "") {
   if (-t STDIN) {
      print "What is the servername you want to setup? ";
      $ip = <STDIN>;
      chomp($ip);
   } else { die "stdin is not a tty and no ip was given to us"; }
}

$ip =~ s/^www\.//g;
print "Scanning httpd.conf.";




die if (! -e "/usr/local/apache/conf/httpd.conf");

$addedhost = 0;
$conflock = SafeFile::safeopen(\*HC,"+<","/usr/local/apache/conf/httpd.conf");
while(<HC>) {
   push(@HC,$_);
}
seek(HC,0,0);
foreach(@HC) {
   if (!/^#/) {
      if (/<virtualhost/i) {
         $bh = 1;
         $ivh = 1;
      }
      if (/<\/virtualhost/i) {
         if ($bh) {
            print HC "\n<IfModule mod_jk.c>\nJkMount /*.jsp ajp13\n" .
               "JkMount /servlet/* ajp13\nJkMount /servlets/* ajp13\n" .
               "</IfModule>\n";
            $addedhost = 1;
         }			
         $ivh = 0;
      }
      if ($ivh) {
         if (/mod_jk/i) {
            $bh = 0;
         }
         if (/ServerName (\S+)/i) {
            $sn = $1;
            $sn =~ s/^www\.//g;
            if ($sn ne $ip) { $bh = 0; }
         }
      }
   }	
   print HC $_;
}
truncate(HC,tell(HC));

SafeFile::safeclose(\*HC,$conflock);


if ($addedhost) {
   system("/scripts/gentomcatlist");
   safeaprestart();
   print ".jsp support installed!\n";
} else {
   print "\n$ip not found or .jsp already installed!\n";
}

sub safeaprestart {
   if (-x "/usr/local/cpanel/bin/safeapacherestart") {
      system("/usr/local/cpanel/bin/safeapacherestart");
   } else {
      if (-x "/usr/bin/killall") {
         system("/usr/bin/killall","-USR1","httpd");
      } elsif (-x "/usr/sbin/killall") {
         system("/usr/sbin/killall","-USR1","httpd");
      } elsif (-x "/sbin/killall") {
         system("/sbin/killall","-USR1","httpd");
      } elsif (-x "/bin/killall") {
         system("/bin/killall","-USR1","httpd");
      } elsif (-x "/usr/local/bin/killall") {
         system("/usr/local/bin/killall","-USR1","httpd");
      } elsif (-x "/usr/local/sbin/killall") {
         system("/usr/local/sbin/killall","-USR1","httpd");
      }
   }
}

