#!/usr/bin/perl

BEGIN {
	push(@INC,"/usr/local/cpanel");
}

use SafeFile;

#VARIBLES
my $domain = '%domain%';
my $installpath = '%installpath%';
my $modulename = '%modulename%';
my $modulepath = '%modulepath%';
my $homedir = '%homedir%';
my $user = '%user%';
my $installdir = '%installdir%';
my $publichtml = '%public_html%';
my $sqldb = '%sqldb%';
my $sqluser = '%sqluser%';
my $sqlpass = '%sqlpass%';
my $sqlserver = '%sqlhost%';
my $username = '%username%';
my $password = '%password%';


my $cpassword = crypt($password,getranddata(16,1));

print "We are installing in $installdir...\n";

system("mv $installdir/pkg/* $installdir/");

system("mysql -u${sqluser} -p${sqlpass} ${sqldb} < $installdir/schemas/mysql.sql");



regsrep("$installdir/index.php","dbtype.*dba","'dbtype'   => 'SQL',");
regsrep("$installdir/index.php","\/\/ For a MySQL database","\n'dsn' => 'mysql://${sqluser}:${sqlpass}\@${sqlserver}/${sqldb}',\n");

regsrep("$installdir/index.php","^define.*THEME","define('THEME', 'MacOSX');");


regsrep("$installdir/index.php","^if.*ADMIN_USER","if (!defined('ADMIN_USER')) define('ADMIN_USER', \"${username}\");");
regsrep("$installdir/index.php","^if.*ADMIN_PASSWD",
"if (!defined('ADMIN_PASSWD')) define('ADMIN_PASSWD', \"${cpassword}\");\nif (!defined('ENCRYPTED_PASSWD')) define('ENCRYPTED_PASSWD', true);");

unlink("$installdir/config.php.tmpeditlib");

system("rm","-rf","$installdir/pkg");

print "<b>Complete!</b>\n";

print "<br>You can access your new PhpWiki installation at: <a href=\"http://$domain/$installpath/\">http://${domain}${installpath}/</a>";
print "<br><br>\n";

sub regsrep {
   my($file,$old,$new) = @_;
   $filelock = SafeFile::safeopen(\*FH,"$file");
   $fileeditlock = SafeFile::safeopen(\*FHT,">$file.tmpeditlib");
   while(<FH>) {
      if ($_ =~ /^$/ || $_ eq "\n" || $_ eq "\r\n") {
         print FHT "$_";
      } elsif($_ =~ /$old/) {
        $result = $1;
         my $mnew = $new;
        $mnew =~ s/\$1/$result/g;
         print FHT "$mnew\n";
      } else {
         print FHT $_;
      }
   }
   SafeFile::safeclose(\*FH,$filelock);
   SafeFile::safeclose(\*FHT,$fileeditlock);
   $fileeditlock = SafeFile::safeopen(\*FHT,"$file.tmpeditlib");
   $filelock = SafeFile::safeopen(\*FH,">$file");
   while(<FHT>) { print FH $_ };
   SafeFile::safeclose(\*FH,$filelock);
   SafeFile::safeclose(\*FHT,$fileeditlock);
}


                                                                                                                      
sub getranddata {
   my($size,$sendheader) = @_;
   my $rndpass;
   if ($size eq "") { $size = 10; }
   my $readsize = ($size * 16);

   open(URAND,"/dev/urandom") || do {
        print "Fatal Error: Unable to read data from /dev/urandom ($!).";
   };
   while(length($rndpass) < $size) {
      read URAND,$rndpass,$readsize;
      $rndpass =~ s/\W//g;
   }
   $rndpass = substr($rndpass,0,$size);
   return($rndpass);
}

