#!/bin/sh
eval 'if [ -x /usr/local/cpanel/3rdparty/bin/perl ]; then exec /usr/local/cpanel/3rdparty/bin/perl -x -- $0 ${1+"$@"}; else exec /usr/bin/perl -x $0 ${1+"$@"}; fi;'
  if 0;

#!/usr/bin/perl

# cpanel - gentomcatlist2                         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

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

use strict;
use Cpanel::SafeFile      ();
use Cpanel::HttpUtils     ();
use Cpanel::EditHttpdconf ();
use Cpanel::FileUtils     ();

print "Scanning httpd.conf.";

my %USERS;
open(UD,"/etc/userdomains");
while(<UD>) {
        s/[\s\n\r]*//g;
        my($domain,$user) = split(/:/, $_);
        $USERS{$domain} = $user;
}
close(UD);

my $httpconf = find_httpconf();

my $xu = 0;
my $vh = 0;
my %JK;
my %SN;
my %SA;
my %DR;
my %nhosts;
my $entries;

open(HTTPDCONF,"$httpconf");
while(<HTTPDCONF>) {
   s/\>//g;

   if ($_ !~ /^\s*#/) {
      if (/^\s*\<virtualhost\s+(\S+)($|\s)/i) {
         print ".";
         $vh = 1;
         $xu++;
      }
      if ($vh == 1) {
         if (/^\s*jkmount/i) {
            $JK{$xu} = 1;
         }
         if (/^\s*WebApp/i) {
            $JK{$xu} = 1;
         }
         if (/^\s*servername\s+(\S+)($|\s)/i) {
#            print ".";
            $SN{$xu} = $1;
         }
         if( /^\s*serveralias\s+(\S+(:?\s+\S+)*)/i ) {
             push @{ $SA{ $xu } }, split(/\s+/, $1);
         }
         if (/^\s*documentroot (\S+)/i) {
#            print "X";
            $DR{$xu} = $1;
         }
      }
      if (/^\s*\<\/virtualhost/i) {
         print ".";
         $vh = 0;
      }
   }
}
close(HTTPDCONF);
print "\n";

my $server_aliases = {};
#  add domain to list if -e /usr/local/apache/conf/userdata/[std|ssl]/{current apapche 1 or 2}/USER/DOMAIN/cp_jkmount.conf
my $apv       = Cpanel::HttpUtils::get_current_apache_version_key() eq '1' ? 1 : 2;
my $vhost_inc = Cpanel::EditHttpdconf::get_hashref_of_domains_with_vhost_include( 'cp_jkmount.conf', $apv, [values %USERS] );
for my $num ( keys %SN ) {
    $JK{$num} = 1 if $vhost_inc->{ $SN{$num} };
    if ( $JK{$num} ) {
        my $sn = $SN{$num};
        $sn =~ s{^www[.]}{};
        if ( exists $SA{ $num } ) {
            # if its not already the www. alias of the servername...
            if ( $SA{ $num } ne 'www.' . $sn ) { 
                $server_aliases->{ $sn } = $SA{ $num };
            }
        }
    }
}

foreach my $server (sort keys %JK) {
   my $s1 = $SN{$server};
   my $s2 = $s1;
   $s2 =~ s/^www\.//g;
   next if ($s2 eq "" || $s1 eq "");

   if ($DR{$server} ne "") {
      $nhosts{$s1} = $DR{$server};
   }
   if ("$s2" ne "$s1") {
      $nhosts{$s2} = $DR{$server};
   }
}

my $tt = '';
my $template_file = '/var/cpanel/templates/tomcat/server.xml.host_entry.default';

# preserve old one if they've not created a new one
if (-e '/etc/gentomcatlist_server_xml_host_entry_template' && !-e $template_file) {
    Cpanel::FileUtils::safemv('/etc/gentomcatlist_server_xml_host_entry_template', $template_file);
}

if (-e $template_file) {
    if (eval { require Template }) {
        $tt = Template->new('ABSOLUTE' => 1) || '';
        if (!$tt) {
            warn "Could not use template: $Template::error"; 
        }
        else {
            warn "!!\nCUSTOM TEMPLATE IN USE\n\nPLEASE VERIFY THAT ALL 'Host' ENTRIES ARE VALID AND UNDUPLICATED\n\nTO BUILD WITH SAFE DEFAULTS RUN THIS COMMAND BEFORE RERUNNING $0::\n\tmv $template_file $template_file.orig\n!!\n";
        }
    }
    else {
        warn "Could not use template: Install Template.pm";
    }
}

foreach my $nhost (sort keys %nhosts) {
    next if $nhost =~ m{www\.}; # do not put extra entry in for www. domains they get aliased in the XML entry below
   my $docbase = $nhosts{$nhost};
   my $tdoc = $docbase;
   $tdoc =~ s/public_html\/$//g;
   $tdoc =~ s/public_html$//g;
   $tdoc .= "webapps";
   if (-d $tdoc) {
      $docbase = $tdoc;
   }
   
   my %server_alias_seen = ("www.$nhost" => 0);
   my @alias_list = ("www.$nhost");
   my $alias = "<Alias>www.$nhost</Alias>\n";
   if ( ref $server_aliases->{ $nhost } eq 'ARRAY' ) {
       # preserve order and make unique ala List::moreUtils::uniq()
       my %uniq;
       @{ $server_aliases->{ $nhost } } = map { $uniq{$_}++ == 0 ? $_ : () } @{ $server_aliases->{ $nhost } };

       for my $serveralias ( @{ $server_aliases->{ $nhost } } ) { 
           next if exists $server_alias_seen{ $serveralias };
           $alias .= "          <Alias>$serveralias</Alias>\n";
           push @alias_list, $serveralias;
           $server_alias_seen{ $serveralias } = 1;
       }
   }
   chomp $alias;

   my $do_hardcoded = 1;

   if ($tt) {
       my $buffer = '';
       if ( $tt->process($template_file, {'name' => $nhost, 'appbase'=>$docbase, 'alias_list' => \@alias_list}, \$buffer) ) {
           $do_hardcoded = 0;
           $entries .= $buffer;
       }
       else {
           warn "Template could not be used: " . $tt->error();
       }
   }

   if ($do_hardcoded) {
       $entries .= <<EOM;
       <Host name="$nhost" appBase="$docbase">
          $alias 
          <Context path="" reloadable="true" docBase="$docbase" debug="1"/>
          <Context path="/manager" debug="0" privileged="true"
              docBase="/usr/local/jakarta/tomcat/server/webapps/manager">
          </Context>
       </Host>
EOM
    }

    if ($USERS{$nhost} ne "") {

        if (my $pid = fork()) {
#master
        } else {
            my $htaccess_file = "${docbase}/WEB-INF/.htaccess";
            setuids($USERS{$nhost});
            if (! -e "${docbase}/WEB-INF") {
               mkdir("${docbase}/WEB-INF",0755);
            }
            if (! -e "${docbase}/WEB-INF/classes") {
               mkdir("${docbase}/WEB-INF/classes",0755);
            }
            if (! -e "${docbase}/WEB-INF/lib") {
               mkdir("${docbase}/WEB-INF/lib",0755);
            }
            if (! -e "${docbase}/WEB-INF/classes/ServletsTestPage.class" &&
                  -e "/usr/local/jakarta/tomcat/samples/ServletsTestPage.class") {
               system("cp","-f","/usr/local/jakarta/tomcat/samples/ServletsTestPage.class",
                     "${docbase}/WEB-INF/classes/ServletsTestPage.class");
            }
            if (! -e "${docbase}/jsptest.jsp" &&
                  -e "/usr/local/jakarta/tomcat/samples/jsptest.jsp") {
               system("cp","-f","/usr/local/jakarta/tomcat/samples/jsptest.jsp",
                     "${docbase}/jsptest.jsp");
            }
            if (! -e $htaccess_file) {
                open my $htaccess_fh, '>', $htaccess_file;
                print $htaccess_fh "deny from all\n";
                close $htaccess_fh;
            }
            else {
                deny_from_all( $htaccess_file );
            }
            exit();
        }
    }
}

my @SO;
my @SOX;
my $inhost = 0;
my $lasthost = 0;
my $line = 1;

my $solock = Cpanel::SafeFile::safeopen(\*SO,"+<","/usr/local/jakarta/tomcat/conf/server.xml");
while(<SO>) {
    
    if ( /\<\!\-\- cp parsing marker \<\/?Host\> do not remove\-\-\>/ ) {
        next;  # do not keep existing ones in case they are out of place or multi
    }

    if (/<\/web\-app>/) {
        push @SOX, 
            "  <!-- cp parsing marker <Host> do not remove -->\n", 
            "  <!-- cp parsing marker </Host> do not remove -->\n",
            ;
    }
    
    push @SOX, $_;
}

foreach  ( @SOX ) {    
   if ( ! $inhost && /<Host/ ) { 
      $inhost = 1;
   }
   if ( $inhost && /<\/Host/) { 
      if ( ! $lasthost ) {
         $lasthost = $line;
         $line++; 
         push(@SO,$_); 
      }
      if ( $lasthost ) {
           $inhost = 0;
           next;
      }
   }
   if ( $lasthost && ! $inhost ) {
       $line++;
       push(@SO,$_);
   } elsif ( $inhost && ! $lasthost ) {
       $line++;
       push(@SO,$_);
   } elsif ( ! $inhost && ! $lasthost  ) {
       $line++;
       push(@SO,$_);
   }
}

seek(SO,0,0);
$line = 0;
foreach (@SO) {
   $line++;
   if ( $line == ($lasthost + 1) ) {
      print SO $entries;
   }
   print SO;
}
truncate(SO,tell(SO));
Cpanel::SafeFile::safeclose(\*SO,$solock);

system("/usr/sbin/stoptomcat");
system("/usr/sbin/starttomcat");

sub find_httpconf {
   my(@LOC,$loc);
   @LOC = ("/usr/local/apache/conf/httpd.conf",
         "/etc/httpd/conf/httpd.conf");
   foreach $loc (@LOC) {
      if (-e $loc) { return $loc; }
   }
   return "";
}

sub setuids {
   my($user) = $_[0];
   my($uid,$gid);
   (undef,undef,$uid,$gid) = getpwnam($user);
   if ( ! ($( = int($gid)) ) {
         print "error setting gid\n";
         exit;
         }

         if ( ! ($) = "$gid $gid") ) {
      print "error setting gid\n";
      exit;
   }
   if (! (($< = $uid) && ($> = $uid)) ) {
      die "error setting uid ($uid) [$user]\n";
   }
   return $uid;
}

sub deny_from_all {
    my $htaccess_file = shift;
    my $all_denied = 0;

    if ( open my $htaccess_fh, '<', $htaccess_file ) {
        while ( my $line = <$htaccess_fh> ) {
            chomp $line;
            if ( $line =~ m/^deny from all$/ ) {
                $all_denied = 1;
            }
            elsif (    $line =~ m/^\s*$/
                    || $line =~ m/^#/ ) {
                # ignoring blank lines and comments
            }
            else {
                $all_denied = 0;
            }
        }
        close $htaccess_fh;
    }

    if ( ! $all_denied
         && open my $htaccess_fh, '>>', $htaccess_file ) {
            print $htaccess_fh "\ndeny from all\n";
            close $htaccess_fh;
    }

    return 1;
}

__END__
