#!/usr/local/bin/perl

#-----------get the javafile & portfile names to be updated 
$pfile='../webflow/frontend/WebModDesctemplate.tmp';
$jfile ='../webflow/modules/demo/HPF/HPFtemplate.tmp';
$modfile = '../modules.txt';
$jname = 'webflow.modules.demo.HPF.HPFMod';
$pname = 'webflow.frontend.WebPort';
#Add your classpath settings here 
#also make sure the javac path is set properly
$cpath ='../';
$javac = "/home/A11E/wavelet/furm/jdk/jdk1.1/bin/javac -classpath $cpath "; 

#---get filename and port number
print "Content-type: text/html\n\n";

$input = $ENV{'QUERY_STRING'};
#print "Query String = $input####\n";

@arr = split(/[&=]/,$input);
$smurl = $arr[1];
$url = $arr[3];
$port = $arr[7];
$project = $arr[5];
 
$urlfile = &get_file_from_url($url);
$project = &get_file_from_url($project);
$proj = $project.$urlfile;
print "Appended string is  = $proj\n";
#@a1= split(/[/]/,$filename); 
#$tmodname=$a1[4];  
#print "Query String = $tmodname\n";
#$modname=~ s/./_/; 
 
$end = (2 * $port) + 8;
for($k=8; $k< $end; $k=$k+2) {
#  print "PRINTING = $arr[k+1]";
   push(@port,$arr[$k+1]);
}




$pnewfile = $pfile;
$pnewfile =~ s/ModDesctemplate/$port/;
$pname=~ s/Port/$port/;
$jname=~ s/Mod/$proj/;
$pnewfile =~ s/tmp/java/;
&replace($pnewfile,$pfile,$port,$url);

$jnewfile = $jfile;
$jnewfile =~ s/template/$proj/;
$jnewfile =~ s/tmp/java/;
&replace($jnewfile,$jfile,$port,$url);
#---------modules.txt file is updated
open(M,">>$modfile");
print M "$jname $smurl $pname\n";
close(M);
#-----------compiling 
#jif($filename != '' && $port != '' ){
open(STDERR,">err.log");
print "Trying to Compile .....\n";
system("$javac $jnewfile");
system("$javac $pnewfile");
close(STDERR);
#}


#-----open the and replaces $port by the string $str1 
#-----and $fname by $str2
sub replace {
local($filename,$tempfile, $str1, $str2) = @_;
@arr = split(/\n/,`cat $tempfile`);


open(W,">$filename");
foreach $l (@arr) {
   if($l =~ /\$ports/) {
      $l =~ s/\$ports/$str1/;
   }elsif($l =~ /\$fname/) {
      $l =~ s/\$fname/$str2/; 
   }elsif($l=~ /\$proj/) {
      $l =~ s/\$proj/$proj/;
   }elsif($l =~ /\$ColorVal/) {
      $l =~ s/\$ColorVal//;
      $cnt = 0;
      foreach $p(@port) {
	print "PORT VAL = $p\n";
         $l .= "CCol[$cnt]=$p;\n";
         $cnt++;
      }
 #     print "l = $l \n";
   }
   print W "$l\n";
}
close(W);
}
#-------------------------------------
sub get_file_from_url() {
local($u) = @_;
$u=~s![^/]*$!!;
$f=$&;
$f=~s!\.config!!;
$f =~ s!\n!!g;
print " The filename from URL is   = $f ###\n";
$f
}
