#!/usr/bin/perl

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

use SafeFile;


if (! -e "/usr/local/apache/libexec/mod_caucho.so") {
   print "Sorry you must install the cPanel Resin addon module.";
   exit;
}


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

$| = 1;

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

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

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

$addedhost = 0;
$conflock = SafeFile::safeopen(\*RC,"+<","/usr/local/resin/conf/resin.conf");
while(<RC>) {
   push(@RC,$_);
}
seek(RC,0,0);
foreach(@RC) {
   if (/   <\/host>/) {
      $host ++;
   }
   if ( $_ =~ "${domain}" ) {
      print "${domain} is already added!";
      exit()
   }
}
seek(RC,0,0);
foreach(@RC) {
   if (/   <\/host>/) {
      $host2 ++;
      if ( $host == $host2 ) {
	$owner = getdomainowner($domain);
	if ( $owner eq "" ) { print "Error! Domain: ${domain} is not on the server\n"; exit(); }
	$homedir = gethomedir($owner);
	print RC "    <\/host>\n    <host id='${domain}'>\n" .
	    "        <host-alias>www.${domain}</host-alias>\n" .
	    "        <web-app id='/' document-directory='${homedir}/public_html/'/>\n" .
	    "        <document-directory>${homedir}/public_html</document-directory>\n";
	 $addedhost = 1;
      }
   
   }
   print RC $_;
}
truncate(RC,tell(RC));

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

if ($addedhost) {
   print "Resin support added for ${domain}!\n";
} else {
   print "\n${domain} not found";
}

sub gethomedir {
   local $_;
   my($user) = @_;
   my($homedir);
   open(PASSWD,"/etc/passwd");
   while(<PASSWD>) {
      if (/^$user:/) {
         (undef,undef,undef,undef,undef,$homedir,undef) = split(/:/, $_,  
7);
         while(-l $homedir) {
                $homedir = readlink($homedir);
         }
         close(PASSWD);
         #$_ = "";
         return($homedir);
      }
   }
   close(PASSWD);


}

sub getdomainowner {
   local $_;
   my($domain) = @_;
   my($user) = '';
   open(USERDOMS,"/etc/userdomains");
   seek(USERDOMS,0,0);
   while(<USERDOMS>) {
      s/\n//g;
      if (/^$domain: (\S+)/) {
         $user = $1;
         last;
      }
   }
   close(USERDOMS);
   return $user;
}

