#!perl
# Import server settings.
# Called by import.
# This script is used for Proxy Server 3.6 to 4.0  migration.

#All the files and directories created by the script are forced to have permissions by chmod(), so that the migration can happen between different user domains.

# to get an unique temp dir name
sub tempdirhash 
{
    my ($str) = @_;
    my $hash = 0;

    foreach $chr (unpack("C*", $str)) 
    {
    	$hash = $hash ^ ($hash << 5) ^ $chr;
    }
    sprintf("%08x", $hash);
}

 
BEGIN 
{
	$rootDir = $ENV{'NETSITE_ROOT'};#3.6 proxy server root
	@INC=("$rootDir/bin/proxy/perl","$rootDir/bin/proxy/install/misc"); #libraries   
	$Port=""; #extracted from magnus.conf moved to server.xml
    	$Security="";#same as above
        $Address="";  #extracted from magnus.conf moved to server.xml
        $ConnAddress=""; #extracted from magnus.conf and assigned to Address
	$shortHost="";	
	$error_log_new="";
	$access_log_old="";
	$access_log_new="";
# SSL migration parameters (magnus.conf -> server.xml)
        $CERTDefaultNickname="Server-Cert";
        $SSL2="on";
        $SSL3="on";
        $SSLClientAuth="off";
        $ssl3Ciphers="";
        $ssl2Ciphers="";
#caching parameters
	$cacheDir="";
	$cacheSize="";
	$status="";
	$ndirs=0;
#Partition details
	@p_dir=();
	@p_status=();
	@minavail=();
	@maxsize=();
	$partitioncount=0;
#gc settings
	$tunegc=0;
	$gchimargin=80;
	$gclomargin=70;
	$gcleavefsfull=60;
	$gcextramargin=30;
#any magnus Init directives
        @magnus_init=();
#bu.conf 
  	$bu_objcount=0;	
	@configname=();
	@date=();
	@starttime=();
	@endtime=();
#userdb setting
	$userdb_entry="default";	
}


use Cgi;
use BinUtil;
use Magnus;

$| = 1; #output_autoflush
$isNT = -d '\\'; #Win/Unix
if ($isNT) 
{
 	$libExt = ".dll";
 	$libPrefix = "";
 	$libLocation = "bin";
 	$os = "WINNT";
 	chomp($hostName = `hostname`);
# hostname is made lowercase on windows just for consistency with other certs.
        $hostName = lc($hostName);
}
else
{
 	$libPrefix = "lib";
 	$libLocation = "lib";
 	chomp($os = `uname -s`);
 	chomp($hostName = `uname -n`);
 	if ($os =~ /HP-UX/) 
 	{
 		$libExt = ".sl";
 	} 
 	else
 	{
  		if (!$os)
  		{
    			print "&nbsp;&nbsp;<FONT COLOR=\"red\">Warning:</FONT> Cannot run <CODE>uname</CODE>.  Assuming this is <B>not</B> an HP machine.\n";
  		}
  		$libExt = ".so";
 	}
}


$binDir = "$rootDir/bin/proxy";
$libDir = "$binDir/$libLocation"; 
$libDir =~ s/\\/\//g if $isNT;
$mysname = $cgiVars{'name'};
$mysname =~ s/^\s+//;  # remove white spaces in the beginning and end
$mysname =~ s/\s+$//;
$sname = "proxy-$mysname";
$bu_update = "$rootDir/extras/bu/bu";
$bu_update =~ s/\//\\/g if $isNT;
$trail = substr($cgiVars{'dir'}, length($cgiVars{'dir'})-1, length($cgiVars{'dir'}));

if ($trail eq "/" || $trail eq "\\") 
{
	chop($cgiVars{'dir'});
}

$newHome = "$rootDir/$sname";
$oldHome = "$cgiVars{'dir'}/$cgiVars{'server'}";
$oldHome =~ tr/\/*/\//s;
$oldRoot="$cgiVars{'dir'}";
$oldRoot =~ tr/\/*/\//s;
$newRoot=$rootDir;
$oldsname="$cgiVars{'server'}";
$oldlibDir = "$oldRoot/bin/proxy/$libLocation";
$error_log_new="$newHome/logs/errors";
$access_log_new="$newHome/logs/access";
$configDir = "$newHome/config";
$configDir =~ s/\//\\/g if $isNT;
if($isNT) 
{

# create NT-specific entries - services should be created for proxy and SOCKS(currently created for instance alone)
	print "\n&nbsp;&nbsp;<b>Creating Registry Keys and Service</b>...\n\n";
	system("$rootDir/bin/proxy/admin/bin/ntregister -r$rootDir -i$sname > nul");
}
else
{
 # create Unix-specific scripts
#	$ldlibrarypath = "\${SERVER_ROOT}/bin/\${PRODUCT_NAME}/lib:";
#	if ($os =~ /AIX/)
 #{
  # AIX requires /usr/lib and /lib to be in the path
	# 		$ldlibrarypath .= "/usr/lib:/lib:";
	#}
	#	$ldlibrarypath .= "\${LD_LIBRARY_PATH}";
 # The following takes the new start/stop/reconfig scripts of 4.0 install
 # directory and places in the config directory with the right paths.
	$binSubDir = "bin/proxy/bin";
 	$libSubDir = "bin/proxy/lib";
	#	$src = "$newRoot/proxy-admserv/start";
	#open(SRC, "<$src") or print "&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT> Cannot read $src: $!\n";
	#while (<SRC>)
	#{
	#		($name,$value) = split(/\=/, $_);
	#		$hash{$name} = $value;
	#		$javaRunTime = $hash{'JAVA_RUNTIME_LIBPATH'};
	#}
	#close (SRC);
 #start,stop,restart,reconfig,rotate,start-sockd,stop-sockd,restart-sockd scripts from templates
 	BinUtil::makeScript("WPS_SERVER_ROOT=$rootDir",
   	       "WPS_SERVER_ID=$sname",  
	       "$rootDir/bin/proxy/install/misc/instance/start.template",
	       "$newHome/start");
	BinUtil::makeScript("WPS_SERVER_ROOT=$rootDir","WPS_SERVER_ID=$sname",
	       "$rootDir/bin/proxy/install/misc/instance/stop.template",
	       "$newHome/stop");
 	BinUtil::makeScript("WPS_SERVER_ROOT=$rootDir","WPS_SERVER_ID=$sname",
		"$rootDir/bin/proxy/install/misc/instance/restart.template",
		"$newHome/restart");
 	BinUtil::makeScript("WPS_SERVER_ROOT=$rootDir","WPS_SERVER_ID=$sname",
		"$rootDir/bin/proxy/install/misc/instance/reconfig.template",
		"$newHome/reconfig");
 	BinUtil::makeScript("$rootDir/bin/proxy/install/misc/instance/rotate.template",
		"$newHome/rotate");
  BinUtil::makeScript("WPS_SERVER_ROOT=$rootDir","WPS_SERVER_ID=$sname","$rootDir/bin/proxy/install/misc/instance/start-sockd.template",
  "$newHome/start-sockd");
 BinUtil::makeScript("WPS_SERVER_ROOT=$rootDir","WPS_SERVER_ID=$sname",
	       "$rootDir/bin/proxy/install/misc/instance/stop-sockd.template",
	       "$newHome/stop-sockd");
 	BinUtil::makeScript("WPS_SERVER_ROOT=$rootDir","WPS_SERVER_ID=$sname",
		"$rootDir/bin/proxy/install/misc/instance/restart-sockd.template",
		"$newHome/restart-sockd");
	 
#	chmod(0755,"$newHome/start");
#	chmod(0755,"$newHome/stop");
#	chmod(0755,"$newHome/restart");
#	chmod(0755,"$newHome/reconfig");
#	chmod(0755,"$newHome/rotate");
}

#create directories
mkdir("$newHome/logs", 0755);
mkdir("$newHome/config", 0700);
mkdir("$newHome/conf_bk", 0700);
mkdir("$newHome/pac",0755);

chmod(0755, "$newHome/logs","$newHome/pac");

print "<BR/>&nbsp;&nbsp;<b>Database settings...</b>";
#If dbswitch.conf contain localdb settings
if ($cgiVars{'isLocalDb'})
{
 	print "<BR/>&nbsp;&nbsp;<CODE>dbswitch.conf</CODE> contains localdb settings not supported by current version of Proxy Server. Hence no content is migrated.\n";
}
else
{
 	print "<BR/>&nbsp;&nbsp;Migrating LDAP settings from <CODE>dbswitch.conf</CODE>....\n";
	copyldap();
}

# handle magnus.conf
print "\n\n&nbsp;&nbsp;<b>Assimilating <CODE>magnus.conf</CODE>...</b>";
BinUtil::copyFile("$oldHome/config/magnus.conf", "$newHome/config/magnus.conf");
copyMconfig36to40();
# strip out obsolete directives
my %obsoleteDirectives =(
		 'RootObject'=>1,
                 'LoadObjects'=>1, 
                 'LDAPConnPool'=>1,
		 'SearchDepth'=>1,
		 'Dyngroups'=>1,                            
		 'SearchTimeLimit'=>1,
		 'BindTimeLimit'=>1,
		 'LdapCheckUp'=>1,
		 'Certfile' =>1,
		 'Keyfile'  =>1,
		 'CertificateChecking'=>1,
		 'ProcessLife'=>1,
		);
removeObsoleteDirectives("$newHome/config/magnus.conf",
                          \%obsoleteDirectives);

# translate paths
BinUtil::fixPaths("$newHome/config/magnus.conf",
	  	   2,
	  	   $oldHome, $oldRoot,
	  	   $newHome, $rootDir,
	  	   "/logs/pid");

$magnus= new Magnus("$newHome/config/magnus.conf");
$oldMagnus = new Magnus("$oldHome/config/magnus.conf");
$hostName=$oldMagnus->value('ServerName');
$magnus->set('ServerID', $sname);   

# Following will change the User, TempDir values in 4.0 magnus.conf
if (!$isNT)
{
 # deal with any user changes
        $user = $oldMagnus->value('User');
 	if ($cgiVars{'user'} and $cgiVars{'user'} ne $user) {
 	$magnus->set('User', $cgiVars{'user'});
}

# edit the TempDir directive
$magnus->set('TempDir', "/tmp/$sname" . "-" . tempdirhash($newHome));
$pidlog = "$newHome/logs/pid";
$magnus->set('PidLog',$pidlog);
}


# this is to write all the magnus-set into magnus.conf
$magnus->flush();


#ACL migration 
print "\n\n&nbsp;&nbsp;<b>Migrating ACL settings...</b>\n";
undef $/;
open(ACLF,$ACLFile);
$acl_temp=<ACLF>;
close(ACLF);

$/="\n";

if ($acl_temp =~ /^\s*(#[^\n]*\n)*\s*$/)
{
	BinUtil::copyFile("$rootDir/bin/proxy/install/misc/instance/httpacl.template","$rootDir/httpacl/generated.${sname}.acl");
	print "&nbsp;&nbsp;ACL file set to default of current version";
}
else
{ 
	system("$rootDir/bin/proxy/admin/bin/aclmigrate $ACLFile $rootDir/httpacl/generated.${sname}.acl");
if ($?)
{print "&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>&nbsp;&nbsp;ACL migration failed\n";
}
else
{
	print "&nbsp;&nbsp;ACL migration completed. Names in the ACL have been classified into both users and groups.\n&nbsp;&nbsp;Please resolve them manually.\n";
	if ($cgiVars{'isLocalDb'})
	{	
		print "\n&nbsp;&nbsp;Please verify whether ACL contains any references to local DB settings, which has been obsoleted in current version.\n";
	}
open(ACLF,">>$rootDir/httpacl/generated.${sname}.acl");
print ACLF "\nacl \"es-internal\";";
print ACLF "\nallow (read, execute, info) user = \"anyone\";";
print ACLF "\ndeny (list, write, delete) user = \"anyone\";\n";
close(ACLF);
}}

BinUtil::copyFile("$rootDir/httpacl/generated.${sname}.acl","$rootDir/httpacl/genwork.${sname}.acl");
chmod(0644,"$rootDir/httpacl/generated.${sname}.acl","$rootDir/httpacl/genwork.${sname}.acl");


#cache setting,creates cache dir of desired size
print "\n\n&nbsp;&nbsp;<b>Cache configuration...</b>";
createCacheDir();


#obj.conf migration
print "\n\n&nbsp;&nbsp;<b>Assimilating <CODE>obj.conf</CODE>...</b>";
copyObjconf36to40();
BinUtil::fixPaths("$newHome/config/obj.conf",
	    	   2,
	  	   $oldHome, $oldRoot,
                   $newHome, $rootDir,'/logs/','/pac/','/ns-icons/','/plugins/','/config/');

print "\n\n&nbsp;&nbsp;<b>Assimilating <CODE>socks5.conf</CODE>...</b>";
BinUtil::copyFile("$oldHome/config/socks5.conf","$newHome/config/socks5.conf");
chmod(0600,"$newHome/config/socks5.conf");
BinUtil::fixPaths("$newHome/config/socks5.conf",1,$oldHome,$newHome,'/logs/');

#bu.conf migration:date/time moved to server.xml
print "\n\n&nbsp;&nbsp;<b>Assimilating <CODE>bu.conf</CODE>...</b>";
copybuconf();
#creates server.xml
print "\n\n&nbsp;&nbsp;<b>Creating <CODE>server.xml</CODE>...</b>";
createDefaultSdotXml();
print "\n\n&nbsp;&nbsp;<b>Other configuration files...</b>";

# copy new files for the migrated server from 4.0 install directory
#print "&nbsp;&nbsp;Creating <CODE>keyfile</CODE>...";
#BinUtil::copyFile("$rootDir/bin/proxy/install/misc/admin/keyfile", "$newHome/config/keyfile");
#chmod(0644,"$newHome/config/keyfile");

#BinUtil::backupFile($newHome, $sname, "keyfile");
#chmod(0644,"$newHome/conf_bk/keyfile","$newHome/conf_bk/keyfile.1");

#copy icp,parent,parray config files as-is
print "\n&nbsp;&nbsp;Copying <CODE>icp.conf</CODE>...";
BinUtil::copyFile("$oldHome/config/icp.conf","$newHome/config/icp.conf");
chmod(0600,"$newHome/config/icp.conf");
print "\n&nbsp;&nbsp;Copying <CODE>parent.pat</CODE>...";
BinUtil::copyFile("$oldHome/config/parent.pat","$newHome/config/parent.pat");
chmod(0600,"$newHome/config/parent.pat");

if ($isNT && (-e "$oldHome/config/ras.conf"))
{
print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">Warning: </FONT> The current version of Proxy Server does not support Remote Access Functionality. <CODE>ras.conf</CODE> will not be migrated.\n";
}

print "\n\n&nbsp;&nbsp;Copying <CODE>parray.pat</CODE>...";
BinUtil::copyFile("$oldHome/config/parray.pat","$newHome/config/parray.pat");
chmod(0600,"$newHome/config/parray.pat");

print "\n&nbsp;&nbsp;Copying <CODE>proxy.pac</CODE>...";
BinUtil::copyFile("$oldHome/pac/proxy.pac","$newHome/pac/proxy.pac");
chmod(0644,"$newHome/pac/proxy.pac");
print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">Important:</FONT> Edit these files if the port number of the migrated server will differ from that of the 3.6 server instance\n"; 


#*.clfilter files
BinUtil::copyFile("$oldHome/config/magnus.conf.clfilter", "$newHome/config/magnus.conf.clfilter");
BinUtil::copyFile("$oldHome/config/obj.conf.clfilter", "$newHome/config/obj.conf.clfilter");
# Create a default server.xml.clfilter 
open(SXML,">>$newHome/config/server.xml.clfilter") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>server.xml.clfilter cannot be created\n";
print SXML <<__UP_TO_THIS_POINT_;
#
# Filter specification for receiving cluster file transfer
#
FILTER=filterobj %OLDFILE% %NEWFILE%
__UP_TO_THIS_POINT_

chmod(0600,"$newHome/config/server.xml.clfilter");
chmod(0600,"$newHome/config/magnus.conf.clfilter");
chmod(0600,"$newHome/config/obj.conf.clfilter");

#certmap.conf and cron.conf
print "\n\n&nbsp;&nbsp;<FONT COLOR=\"red\">Warning: </FONT><CODE>certmap.conf</CODE> and<CODE> ns-cron.conf</CODE> are not migrated.";


# copy mime types
print "\n\n&nbsp;&nbsp;Copying <CODE>mime.types</CODE>...\n";
BinUtil::copyFile("$binDir/install/misc/instance/mime.types.template", "$newHome/config/mime.types");
chmod(0600,"$newHome/config/mime.types");
print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">Warning : </FONT><CODE>mime.types</CODE> has been set to the default for the current version.\n&nbsp;&nbsp Pls check with <CODE>$oldHome/config/mime.types</CODE> for any missing types.\n"; 

# copy snmp.conf
if (-e "$oldHome/config/snmp.conf") 
{
print "\n&nbsp;&nbsp;Assimilating <CODE>snmp.conf</CODE>...<BR/>";
open(OLDSNMP,"<$oldHome/config/snmp.conf");
open(NEWSNMP,">$newHome/config/snmp.conf");
while( $line = <OLDSNMP>)
{
	if ($line =~ m/MASTERHOST/) {
	    $line = "MASTERHOST $mysname\n";
	}
	print NEWSNMP $line;
}
close(OLDSNMP);
close(NEWSNMP);
chmod(0600,"$newHome/config/snmp.conf");

if(!$isNT) 
{
chown((getpwnam($cgiVars{'user'}))[2, 3],"$newHome/config/snmp.conf");
}
}
BinUtil::copyFile("$rootDir/httpacl/generated.${sname}.acl","$newHome/conf_bk/${sname}.acl.1");
BinUtil::backupFile($newHome,$sname,"server.xml","magnus.conf","obj.conf","mime.types","bu.conf","icp.conf","parray.pat","parent.pat","server.xml.clfilter","magnus.conf.clfilter","obj.conf.clfilter","socks5.conf");
chmod(0600,"$newHome/conf_bk/${sname}.acl.1","$newHome/conf_bk/backups.conf","$newHome/conf_bk/magnus.conf","$newHome/conf_bk/magnus.conf.1","$newHome/conf_bk/obj.conf","$newHome/conf_bk/obj.conf.1","$newHome/conf_bk/obj.conf.1","$newHome/conf_bk/bu.conf","$newHome/conf_bk/bu.conf.1","$newHome/conf_bk/server.xml","$newHome/conf_bk/server.xml.1","$newHome/conf_bk/icp.conf","$newHome/conf_bk/icp.conf.1","$newHome/conf_bk/parent.pat","$newHome/conf_bk/parent.pat.1","$newHome/conf_bk/parray.pat","$newHome/conf_bk/parray.pat.1","$newHome/conf_bk/server.xml.clfilter","$newHome/conf_bk/server.xml.clfilter.1","$newHome/conf_bk/magnus.conf.clfilter","$newHome/conf_bk/magnus.conf.clfilter.1","$newHome/conf_bk/obj.conf.clfilter","$newHome/conf_bk/obj.conf.clfilter.1","$newHome/conf_bk/socks5.conf","$newHome/conf_bk/socks5.conf.1","$newHome/conf_bk/mime.types","$newHome/conf_bk/mime.types.1");

exit;



#to remove directives not supported by 4.0 magnus.conf
sub removeObsoleteDirectives 
{
	my $file = shift;
	my $obsolete = shift;
	my @data = ();
	my $directive;
	my $count_init=0;
        open(FILE, $file) or
	print "&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT> Cannot read $file: $!\n";
        print "\n&nbsp;&nbsp;Directives obsoleted : \n&nbsp;&nbsp;";
        while (<FILE>) 
        {	($directive) = split(/\s/, $_);
		push(@data, $_) unless exists($obsolete->{"$directive"});
		if ($obsolete->{"$directive"})
		{
			print "<CODE>$directive</CODE>&nbsp;";
                	$count_init++;
			if ($count_init==7)
			{
				print "<BR/>&nbsp;&nbsp;";
			}	
		}
	}
	close(FILE);
	open(FILE, "> $file") or
	print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT> Cannot edit $file: $!\n";
	print FILE @data;
	close(FILE);
}


#copies bu.conf - date,time moved to server.xml 
sub copybuconf
{
	open (OLDBCONF,"<$oldHome/config/bu.conf") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>bu.conf cannot be copied\n";
	open(NEWBCONF,">$newHome/config/bu.conf") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>bu.conf cannot be created \n";
	chmod(0600,"$newHome/config/bu.conf");
	while (<OLDBCONF>)
	{       
		if (/<\/Object>/)
		{
			$bu_objcount++;
		}	 	
		if (/^\s*<Object name\s*=\s*([^\s>]+)/)
		{
			$configname[$bu_objcount]=$1;
		}
		if (/^\s*Days\s+(.*)/)
		{
		 	$days[$bu_objcount]=$1;
			chomp($days[$bu_objcount]);
			$days[$bu_objcount]=~ s/\s+/ /g;
			next;	
		}

		elsif (/^\s*Time\s+([^\s-]+)\s*-\s*([^\s-]+)/)
   	 	{
		 	
			$starttime[$bu_objcount]=$1;
			$endtime[$bu_objcount]=$2;
			next;
		}
  		print NEWBCONF $_;
	}
	close(OLDBCONF);
	close(NEWBCONF);
}
 
#copies magnus.conf 

sub copyMconfig36to40
{
	open(OLDMCONF,"<$oldHome/config/magnus.conf") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT> magnus.conf cannot be copied\n";
	open(NEWMCONF,">$newHome/config/magnus.conf") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT> magnus.conf cannot be created \n";
	chmod(0600,"$newHome/config/magnus.conf");
	print NEWMCONF "NetsiteRoot $rootDir\n";
	while(<OLDMCONF>)
	{ 
		if($_ !~ /^\s*Port\s+/)
		{
			if($_ =~ /^\s*SSL2\s+/)
			{
				chomp($_);
				($ignore,$SSL2)=split(/\s+/,$_);
				$SSL2 =~ s/\s+//g;
				next;
			}
			elsif($_ =~ /^\s*ACLFile\s+/)
			{
				chomp($_);
				($ignore,$ACLFile)=split(/\s+/,$_);
				$ACLFile =~ s/\s+//g;
				next;
			}
			elsif($_ =~ /^\s*SSL3\s+/)
			{
				chomp($_);
				($ignore,$SSL3)=split(/\s+/,$_);
				$SSL3 =~ s/\s+//g;
				next;
			}
			elsif($_ =~ /^\s*SSLClientAuth\s+/)
			{
				chomp($_);
				($ignore,$SSLClientAuth)=split(/\s+/,$_);
				$SSLClientAuth =~ s/\s+//g;
				next;
			}
		
			elsif($_ =~ /^\s*SSL3Ciphers\s+/)
			{
				chomp($_);
				($ignore,$ssl3Ciphers)=split(/\s+/,$_);
				$ssl3Ciphers =~ s/\s+//g;
				next;
			}
			elsif($_ =~ /^\s*Ciphers\s+/)
			{
				chomp($_);
				($ignore,$ssl2Ciphers)=split(/\s+/,$_);
				$ssl2Ciphers =~ s/\s+//g;
				next;
			}
			elsif($_ =~ /^\s*Security\s+/)
			{ 	
				chomp($_);
				($ignore,$Security)=split(/\s+/,$_);
				print NEWMCONF "$_\n";
				next;
			}
			elsif($_ =~ /^\s*Address\s+/)
                        {
                                chomp($_);
		        	($ignore,$Address)=split(/\s+/,$_);
                                next;
                        }
			elsif($_ =~ /^\s*ConnAddress\s+/)
			{
				chomp($_);
				($ignore,$ConnAddress)=split(/\s+/,$_);
				next;
			}
			elsif($_ =~/^\s*ErrorLog\s+/)
			{
				next;	
			}
			elsif ($_ =~/^\s*Init\s+/)
			{
				chomp($_); 
				push(@magnus_init,$_);
        next;
			}
			elsif ($_ =~/^\s*#*ServerRoot\s+/)
			{ next;
			}		
		 	elsif($_ =~ /^\s*MaxProcs\s+/)
      			{
      				next;
      			}	
	
			print NEWMCONF $_;
		}
		else
		{
			chomp($_);
			($ignore,$Port)=split(/\s/,$_);
		}
	}
	print NEWMCONF "RqThrottle 128\n";#yet-to-be-done : new entries 
        if ($ConnAddress)
        {
        	print NEWMCONF "Address $ConnAddress\n";
        }
	if ($isNT)
	{	
		print NEWMCONF "ExtraPath $binDir/bin\n";
	}	
  else
	{
			print NEWMCONF "StackSize 131072\n"; 
	}
	close(OLDMCONF);
	close(NEWMCONF);
	copyMagnusInits();
}

#to copy any Init directives that exist in openeopened to obj.conf
sub copyMagnusInits()
{	open(OLDOCONF,"<$oldHome/config/obj.conf")or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>obj.conf cannot be copied\n";
	open(NEWOCONF,">$newHome/config/obj.conf.tmp") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>Temporary obj.conf file cannot be created\n";
	chmod(0600,"$newHome/config/obj.conf.tmp");
	my $init_c=0;
	foreach (@magnus_init)
	{ 
		$init_c=1;
		if ($init_c==1)
		{
			print "\n&nbsp;&nbsp;Init directives exist in magnus.conf of the 3.6 Proxy Server.\n&nbsp;&nbsp;They are being migrated over to obj.conf of the new server";
		}
		print NEWOCONF $_."\n";
	}
	while (<OLDOCONF>)
	{
	 print NEWOCONF $_;
	}
	close(NEWOCONF);
	close(OLDOCONF);
}


#copies obj.conf and extracts info to be migrated to server.xml 
sub copyObjconf36to40
{
	open(OLDOCONF,"<$newHome/config/obj.conf.tmp") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>Temporary obj.conf file cannot be opened\n";
	open(NEWOCONF,">$newHome/config/obj.conf") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>obj.conf cannot be created\n";
	chmod(0600, "$newHome/config/obj.conf");
        my $first_init=0;
	my @params = ();
	my $partitioncount=0;
        while(<OLDOCONF>)
	{ 
       		if (/Init/)
       		{     
			     	 
			if (/load-types/)
	    		{
	     			chomp($_);
				 next;
	    		}
		  	elsif (/init-dns-cache/)
			{
				print NEWOCONF "Init fn=\"host-dns-cache-init\" cache-size=\"1024\" expire=\"1200\" negative-dns-cache=\"yes\"\n";
				next;
			}	
		  	elsif (/parray\.(so|dll)/)
			{   	print NEWOCONF "Init fn=\"load-modules\" shlib_flags=\"(global|now)\" shlib=\"$rootDir/plugins/parray/";	
				if ($isNT)
				{
					print NEWOCONF "parray.dll\"\n";	
				}
				else
				{
					print NEWOCONF "libparray.so\"\n";	
				}
		  	
				next;	
			}
   	elsif (/(set-status-fn=\"?pa-set-member-status\"?)/)
			{
                         $_ =~ s/$1//;	
			 $_ =~ s/$/ LateInit=\"yes\"/;
			}
			elsif (/init-cache/)
			#to accomodate reordering in the directive
	   		{
				
	     			/status=\"?(on|off)\"?\s+/; 
	     			$status=$1;
	     			$p_status[0]="true";
				$maxsize[0]=100;
				$minavail[0]=0;
				next;
			}
			
			elsif (/flex-init/)
			{		
				if (/\s+access=\"(\S+)\"/)
				{
					$access_log_old=$1;
					$_ =~ s/$access_log_old/\$accesslog/;
				}
			}

			elsif (/tune-cache/)
			{
				@params=split;
				print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">Warning:</FONT><CODE> obj.conf: Init tune-cache </CODE> directive : the following parameters are not supported by current version of Proxy Server, hence not migrated :\n";	

				foreach $_ (@params)
				{ 	if ((/min-sync-interval/)||
					    (/notify-block-chunk-per-proc/)||
				            (/update-after-percent/)||
				            (/cmon-tick-interval/)||
					    (/sync-dump-ticks/))
					{	print "&nbsp;&nbsp;<CODE>$_</CODE>\n";
						next;
					}
					else 
					{
						print NEWOCONF "$_ ";
					}
				}
				print NEWOCONF "\n";
				next;
			}
			elsif (/init-partition/)
			{
				$p_status[$partitioncount]="true";
				$maxsize[$partitioncount]=100;
				$minavail[$partitioncount]=0;
				
				/status=\"?(on|off)\"?\s+/;
				$p_status[$partitioncount]=$1;
			        /dir=\"(\S+)\"/;
                                $p_dir[$partitioncount]=$1;
				if (/max-size=\"?(\d+)\"?\s+/)
				{
					$maxsize[$partitioncount]=$1;
				}
				if (/min-avail=\"?(\d+)\"?\s+/)
				{
					$minavail[$partitioncount]=$1;
				}
				if ($partitioncount)
				{
					if ($partitioncount==1)
					{
						print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">Warning:</FONT><CODE> obj.conf</CODE>: There exists more than one partitions on the 3.6 Proxy Server, which will not be migrated.\n&nbsp;&nbsp;Partitions are to be reconfigured through the Administration Server.\n"; 	
					}
			        print "&nbsp;&nbsp;<CODE>Partition $partitioncount : dir=$p_dir[$partitioncount]\tstatus=$p_status[$partitioncount]\tmax-size=$maxsize[$partitioncount]\tmin-avail=$minavail[$partitioncount]</CODE>\n";
				}	
				else
				{
					print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">Warning:</FONT> Cache directory settings as present in <CODE>obj.conf</CODE> are being carried forward to the new Proxy Server.\n&nbsp;&nbsp;They may be edited through the Administration Server interface \n";
				  	print "&nbsp;&nbsp;<CODE>status : $p_status[0]\tmax-size : $maxsize[0]\t min-avail : $minavail[0]</CODE>";
				}
				$partitioncount++;
				next;
			}
			elsif (/tune-gc/)
			{
				
				$tunegc=1;
				if (/gc-hi-margin-percent=\"?(\d+)\"?\s+/)
				{
					$gchimargin=$1;
				}
				if (/gc-lo-margin-percent=\"?(\d+)\"?\s+/)
				{
					$gclomargin=$1;
				}
				if (/gc-leave-fs-full-percent=\"?(\d+)\"?\s+/)
				{
					$gcleavefsfull=$1;
				}
				if (/gc-extra-margin-percent=\"?(\d+)\"?\s+/)
				{
					$gcextramargin=$1;
				}
				next;
			}

			elsif (/init-urldb/)
			{
				print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">Warning:</FONT><CODE>init-urldb</CODE> directive is not supported by current version, hence not migrated";
				next;
			}
			elsif (/init-batch-update/)
			{
				print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">Warning:</FONT><CODE>init-batch-update</CODE> directive is not	supported by current version, hence not migrated";	                	
				next;
			}
			elsif (/icp\./)
			{
				  if ($isNT)
					{
							$_ =~ s/bin\/proxy/plugins\/icp/;
					}
					else
					{
						$_ =~ s/icp\.so/libicp\.so/;
					}
			}		
		}
                elsif (/<Object ppath="http:/ ... /<\/Object>/) {
                             if (/proxy-retrieve/) {
                                 s/proxy-retrieve/proxy-retrieve method="*"/;
                             }
		}
		elsif (/^\s*\#.*$/)
		{ 
			next;
		}   
		elsif (/AddLog fn=\"?urldb-record\"?/)
                { 
			chomp($_);
			next;
		
		}
		elsif (/fn=\"?http-config\"?/)
		{
			next;
		}	
		
		
		print NEWOCONF $_;
	}
	close(OLDOCONF);
	close(NEWOCONF);
	unlink("$newHome/config/obj.conf.tmp") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>Temporary file could not be deleted\n";
}



#create cache directory structure
sub createCacheDir
{
 	$cacheDir=$cgiVars{'cachedir'};
 	if ($cacheDir =~ /^<default>$/)
	{
		$cacheDir="$newHome/cache";
	}
	$cacheSize=$cgiVars{'cachesize'};
 	my @subDirs=("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","_",",",0...9);

print "\n&nbsp;&nbsp;Creating cache directory <CODE>$cacheDir</CODE> of size $cacheSize MB...\n";
	mkdir($cacheDir) or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>$cacheDir cannot be created \n";
 	chmod(0755,$cacheDir);
        mkdir("$cacheDir/.cache-data") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>$cacheDir/.cache-data could not be created";
        if (!$isNT)
	{
 	chown((getpwnam($cgiVars{'user'}))[2,3],"$cacheDir/.cache-data");
	}				 
	chmod(0755,"$cacheDir/.cache-data");
	$ndirs=$cacheSize/125;
 	$dim=log($ndirs)/log(2);
 	for ($i=0;$i<$ndirs;$i++)
 	{
 		if ($dim <= 3)
      		{
      			$dirname=sprintf("s%d\.%d",$dim,$i);
      		}
      		elsif ($dim <= 6)
      		{
      			$dirname=sprintf("s%d\.%02d",$dim,$i);
      		}
      		elsif ($dim <= 8)
      		{
      			$dirname=sprintf("s%d\.%03d",$dim,$i);
      		}
		mkdir("$cacheDir/$dirname")or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>$cacheDir/$dirname cannot be created \n";
		chmod(0755,"$cacheDir/$dirname");
		 		
		foreach  (@subDirs)
 		{       $var=sprintf("%X",ord($_));
  			mkdir("$cacheDir/$dirname/$var") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>$cacheDir/$dirname/$var cannot be created \n";
			chmod(0755,"$cacheDir/$dirname/$var");
			if (!$isNT)
			{
				chown((getpwnam($cgiVars{'user'}))[2,3],"$cacheDir/$dirname/$var");
			}

		}
		if (!$isNT)
		{
			chown((getpwnam($cgiVars{'user'}))[2,3],"$cacheDir/$dirname");
		}

 	}
	if (!$isNT)
	{
		chown((getpwnam($cgiVars{'user'}))[2,3],"$cacheDir");
	}
}


# creates default server.xml

sub createDefaultSdotXml
{

	open(SXML,">$newHome/config/server.xml") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>server.xml cannot be created\n";
	chmod(0600,"$newHome/config/server.xml");

	$dtdRoot = $binDir;
	$dtdRoot =~ s/\\/\//g;

	if ($isNT) 
	{
		$dtdFile="file:///$dtdRoot/dtds/sun-web-proxy-server_4_0.dtd";
	} 
	else 
	{
		$dtdFile="file://$binDir/dtds/sun-web-proxy-server_4_0.dtd";
	}

        if ($Address eq "")
        {
            $Address = "0.0.0.0";
        }

	print SXML <<__UP_TO_THIS_POINT_;
<?xml version="1.0" encoding="UTF-8"?>

<!--
Copyright (c) 2003 Sun Microsystems, Inc.  All rights reserved.
Use is subject to license terms.
-->

<!DOCTYPE SERVER PUBLIC "-//Sun Microsystems Inc.//DTD Sun Java System Web Proxy Server 4.0//EN" "$dtdFile">

<SERVER>
<PROPERTY name="accesslog" value="$access_log_new"/>
<LS id="ls1" ip="$Address" port="$Port" security="$Security" servername="$hostName">
__UP_TO_THIS_POINT_
	if($Security eq "on")
	{
		print SXML "<SSLPARAMS servercertnickname=\"$CERTDefaultNickname\" ssl2=\"$SSL2\" ssl2ciphers=\"$ssl2Ciphers\" ssl3=\"$SSL3\" ssl3tlsciphers=\"$ssl3Ciphers\" tls=\"on\" tlsrollback=\"on\" clientauth=\"$SSLClientAuth\" />\n";
	}
print SXML <<__UP_TO_THIS_POINT_;
</LS>
<MIME id="mime1" file="mime.types" />
<ACLFILE id="acl1" file="$rootDir/httpacl/generated.${sname}.acl"/>
<USERDB id="$userdb_entry" database="$userdb_entry"/>
<FILECACHE enabled="true" transmitfile="false" contentcache="true" maxage="30" mediumfilesizelimit="537600" mediumfilespace="10485760" smallfilesizelimit="2048" smallfilespace="1048576" maxfiles="1024" hashinitsize="0"/>
__UP_TO_THIS_POINT_
	if ($status)
	{
		print SXML "<CACHE enabled=\"$status\" cachedir=\"$cacheDir\" cachecapacity=\"$cacheSize\">\n";
		print SXML "<PARTITION partitiondir=\"$cacheDir\" partitionname=\"default\" maxsize=\"$maxsize[0]\" minspace=\"$minavail[0]\" enabled=\"$p_status[0]\"/>\n";
	print SXML "</CACHE>\n";
        }
	if ($tunegc)
	{
		print SXML "<GC gchimargin=\"$gchimargin\" gclomargin=\"$gclomargin\" gcleavefsfull=\"$gcleavefsfull\" gcextramargin=\"$gcextramargin\" mode=\"automatic\"/>\n";
	}
	print SXML "<LOG file=\"$error_log_new\" loglevel=\"info\"/>\n";

for($i=0;$i<$bu_objcount;$i++)
{
print SXML <<__UP_TO_THIS_POINT_;
<EVENT name="BatchUpdate" enabled="on">
  <EVENTTIME>
    <TIMEOFDAY>$starttime[$i]</TIMEOFDAY>
    <DAYOFWEEK>$days[$i]</DAYOFWEEK>
  </EVENTTIME>
  <EVENTACTION>
    <COMMAND>$bu_update -n $hostName -p $Port -o $configname[$i] -d $configDir</COMMAND>
  </EVENTACTION>
  <PROPERTY name="config" value="$configname[$i]"/>
</EVENT>
__UP_TO_THIS_POINT_
}
        print SXML "</SERVER>\n";
	close(SXML);

}

sub copyldap
{
	open(OLDDBCONF,"<$oldRoot/userdb/dbswitch.conf") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>dbswitch.conf cannot be opened\n";
	open(NEWDBCONF,"<$rootDir/userdb/dbswitch.conf") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>dbswitch.conf cannot be opened\n";
	undef $/;
        $line=<OLDDBCONF>;
	my $present=0;
	my $new=0;
        my $default_exists=0;
	$line =~/directory default (ldap.*)\s/; 
        my $ldap_setting=$1;
        my $ldap_mapping;
        my $default_name="ldap_migration"; 
        $found = 1;
        $count =1;
        $temp = <NEWDBCONF>;
        while ($found)
        {
          if ($temp =~ /([^\s]+)\s($default_name)/)
              {$found =1;
               $default_name="ldap_migration"."-$count";
               $count ++;
              }
          else {$found =0;}
         } 
         
        close(NEWDBCONF);
        $/="\n";
        open(NEWDBCONF,"<$rootDir/userdb/dbswitch.conf") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>dbswitch.conf cannot be opened\n";
        while (<NEWDBCONF>)
	{	
         if ($_ =~ /default null/)
		{	
			$new=1;
			last;
		}   	
	elsif ($_ =~ /^directory\s([^\s]+)\s$ldap_setting$/)
		{       $ldap_mapping=$1; 
		 	$userdb_entry=$1;	
			$present=1;
                        if (!($_ =~ /$line/))
 {print "&nbsp;&nbsp;The LDAP settings already exist in the dbswitch.conf under the name : $ldap_mapping.";
if (!($ldap_mapping eq "default"))
{print "<BR/>&nbsp;&nbsp;Please change any references to \"default\" in the ACL file to \"$ldap_mapping\".";} 		
 }
		last;
}
          
}
	if (!$present)
	{
		if (!$new)
		{
			close(NEWDBCONF);
			open(NEWDBCONF,">>$rootDir/userdb/dbswitch.conf") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>dbswitch.conf cannot be appended\n";
		 	$line =~ s/directory default/directory $default_name/;
			$line =~ s/default:/$default_name:/g;
			$userdb_entry=$default_name;
    print "&nbsp;&nbsp;LDAP settings migrated from 3.6 to the current version under the name \"$default_name\".<BR/>&nbsp;&nbsp;Please change any references to \"default\" in the ACL file to \"$default_name\"."; 	
			print NEWDBCONF "$line";
		}
		else
		{
			close(NEWDBCONF);
			open (NEWDBCONF,">$rootDir/userdb/dbswitch.conf") or print "\n&nbsp;&nbsp;<FONT COLOR=\"red\">[Error]</FONT>dbswitch.conf cannot be written\n";
			print NEWDBCONF $line;
		}
	}
	close (NEWDBCONF);
	close (OLDDBCONF);
}

