my $env=0;

if ($ENV{TC_ROOT} eq "") {
	print "Initialiser TC_ROOT avant de lancer le script\n";
	$env = 1;
}

if ($ENV{TC_DATA} eq "") {
	print "Initialiser TC_DATA avant de lancer le script\n";
	$env = 1;
}

if ($env == 1) {
	exit 1;
}

my $myversion="${project.version}";
my $to_soa = $ENV{TC_DATA}."/soa/";
my $to_bin = $ENV{TC_ROOT}."/bin/";
my $args=0;
my $usr="";
my $pwd="";
my $grp="";

$numArgs = $#ARGV + 1;

foreach $argnum (0 .. $#ARGV) {
	$arg = $ARGV[$argnum];
	if ($arg =~ m/^-u=/) {
		$args = $args + 1;
		$usr = $arg;
		$usr =~ s/^-u=//;
	}
	if ($arg =~ m/^-p=/) {
		$args = $args + 1;
		$pwd = $arg;
		$pwd =~ s/^-p=//;
	}
	if ($arg =~ m/^-g=/) {
		$args = $args + 1;
		$grp = $arg;
		$grp =~ s/^-g=//;
	}
}

if ($args != 3 || $usr eq "" || $pwd eq "" || $grp eq "") {
		print "Utilisation 'perl report_install.pl -u=<usr> -p=<pwd> -g=<grp>'\n";
		print "  -u : login utilisateur dba\n";
		print "  -p : mot de passe\n";
		print "  -g : groupe dba\n";
		exit 1;
}

my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
my $datedujour =  $mday."/".($mon+1)."/".(1900+$year)."-".$hour.":".$min.":".$sec;
my $suffixe = (1900+$year).($mon+1).$mday.$hour.$min.$sec; 

system "echo '------- INSTALLATION REPORT v" .$myversion. " -------'";

system "echo '  Import des reports'";

my $repertoireReports = "./data/reports";
opendir fh_rep, $repertoireReports or die "impossible d'ouvrir le r�pertoire ".$repertoireReports."\n";

my $reportId = "";
system "echo 'Import de la definition des rapports'";
while( ($filename = readdir(fh_rep))){
    next if ($filename eq "." or $filename eq "..");
    $reportId = $filename;
	system "echo ' + Import de ".$reportId."'";
    system "import_export_reports -import -u=".$usr." -p=".$pwd." -g=".$grp." -v -overwrite -stageDir=./data/reports -reportId=\"".$reportId."\"";
}
closedir fh_rep or die "Impossible de fermer le r�pertoire ".$repertoireReports."\n";

system "echo 'Import des queries'";

my $repertoireQueries = "./data/queries";
opendir fh_rep, $repertoireQueries or die "impossible d'ouvrir le r�pertoire ".$repertoireQueries."\n";
	my @fic_rep_list = grep { !/^\.\.?$/ } readdir fh_rep;
closedir fh_rep or die "Impossible de fermer le r�pertoire ".$repertoireQueries."\n";

concat_query_files($repertoireQueries);
system "echo '  Import des requetes en une fois'";
$target=$repertoireQueries."/all_queries.xml";
if (-e $target){
	system "plmxml_import -u=".$usr." -p=".$pwd." -g=".$grp." -import_mode=overwrite -xml_file=".$target;
}
else {
	print "File ".$target." cannot be found\n";
}

system "echo '  Import des policies'";
copy_policy_files("./data/policies");

system "echo '  Import du binaire d encryptage";
system "cp ./data/bin/encrypt ".$to_bin;
system "chmod 755 ".$to_bin."encrypt";


system "echo 'Import de la pr�f�rence report'";
system "preferences_manager -u=".$usr." -p=".$pwd." -g=".$grp." -mode=import -scope=SITE -file=./data/report_prefs.xml -action=OVERRIDE";
 
system "preferences_manager -u=" .$usr. " -p=" .$pwd. " -g=" .$grp. " -mode=import -preference=\"PV SNECMA Reports deployment date\" -scope=SITE -values=" .$datedujour. " -action=OVERRIDE";
system "preferences_manager -u=" .$usr. " -p=" .$pwd. " -g=" .$grp. " -mode=import -preference=\"PV SNECMA Reports version\" -scope=SITE -values=" .$myversion. " -action=OVERRIDE";

system "echo '  Import des Regles de Revision'";

system "plmxml_import -u=" .$usr. " -p=" .$pwd. " -g=" .$grp. " -xml_file=./data/revision_rule/revisionrule.xml -import_mode=overwrite";

system "echo '----- FIN INSTALLATION REPORT v" .$myversion. " -------'";

sub promptUser {
   #-------------------------------------------------------------------#
   #  two possible input arguments - $promptString, and $defaultValue  #
   #  make the input arguments local variables.                        #
   #-------------------------------------------------------------------#

   local($promptString,$defaultValue) = @_;

   #-------------------------------------------------------------------#
   #  if there is a default value, use the first print statement; if   #
   #  no default is provided, print the second string.                 #
   #-------------------------------------------------------------------#

   if ($defaultValue) {
      print $promptString, "[", $defaultValue, "]: ";
   } else {
      print $promptString, ": ";
   }

   $| = 1;               # force a flush after our print
   $_ = <STDIN>;         # get the input from STDIN (presumably the keyboard)


   #------------------------------------------------------------------#
   # remove the newline character from the end of the input the user  #
   # gave us.                                                         #
   #------------------------------------------------------------------#

   chomp;

   #-----------------------------------------------------------------#
   #  if we had a $default value, and the user gave us input, then   #
   #  return the input; if we had a default, and they gave us no     #
   #  no input, return the $defaultValue.                            #
   #                                                                 # 
   #  if we did not have a default value, then just return whatever  #
   #  the user gave us.  if they just hit the <enter> key,           #
   #  the calling routine will have to deal with that.               #
   #-----------------------------------------------------------------#

   if ("$defaultValue") {
      return $_ ? $_ : $defaultValue;    # return $_ if it has a value
   } else {
      return $_;
   }
}

sub copy_policy_files{
	#
	# Copie toutes les policies dans tous les sous-dossiers vers le dossier SOA, *a plat*
	# system "cp -Rf ./data/policies/reports/SOME_FOLDER/SOME_FILE.xml " . $to_soa;

	my $source_dir = $_[0];
	
	print "Import de la policy: dossier = ".$source_dir."\n";

	# entete du fichier genere
	opendir fh_rep, $source_dir or die "impossible d'ouvrir le r�pertoire ".$source_dir."\n";
		my @fic_rep_list = grep { !/^\.\.?$/ } readdir fh_rep;
	closedir fh_rep or die "Impossible de fermer le r�pertoire ".$source_dir."\n";
	
	# Browse all the folder"s content
	foreach my $elem ( @fic_rep_list) {
		# Skipping files begginning whith . or .svn
		my $absoluteElem = $source_dir . '/'.$elem;
		if ($elem!~/^\./ and $elem!~/.svn/) {
			# If the file is a directory
			if (-d $absoluteElem) {
				# Here is where we recurse.
				# This makes a new call to process_files()
				# using a new directory we just found.
				copy_policy_files ($absoluteElem);
			} else { 
				# If it isn't a directory, lets just do some
				# processing on it.
				print "  Import de la policy: ".$elem."\n";
				system "cp -Rf ".$absoluteElem." ".$to_soa."/policies";
			}
		}else{
			print "  Element ".$absoluteElem." ignor�\n";
		}
	}
}

sub concat_query_files{
	#
	# all-queries.pl
	#
	# concat�ne toutes les queries en 1 seul fichier

	my $source_dir = $_[0];
	#printf("$ARGV[0]");
	#print("--------------------------");

	# entete du fichier genere
	opendir fh_rep, $source_dir or die "impossible d'ouvrir le r�pertoire ".$source_dir."\n";
		my @fic_rep_list = grep { !/^\.\.?$/ } readdir fh_rep;
	closedir fh_rep or die "Impossible de fermer le r�pertoire ".$source_dir."\n";

	open (OUTPUTFILE, "> ".$source_dir."/all_queries.xml") || die "Can't write in ".$outputFile." : $!";
	print OUTPUTFILE "<?xml version=\"1.0\"  encoding=\"utf-8\"?>\n";
	print OUTPUTFILE "<plmxml_bus:PLMXMLBusinessTypes xmlns=\"http://www.plmxml.org/Schemas/PLMXMLSchema\"\n";
	print OUTPUTFILE " xmlns:plmxml_bus=\"http://www.plmxml.org/Schemas/PLMXMLBusinessSchema\"\n";
	print OUTPUTFILE " schemaVersion=\"6\" language=\"fr-fr\" date=\"2014-07-04\" languages=\"en-us fr-fr de-de it-it es-es pt-br\" time=\"14:20:53\" author=\"unset\">\n";

	for $j (0..((scalar @fic_rep_list) -1) ) 
	{
		if ( $fic_rep_list[$j] eq "delete_queries.xml" || $fic_rep_list[$j] eq "all_queries.xml" || $fic_rep_list[$j] eq ".svn") 
		{
			print "skipping query no ".($j+1)."/".scalar @fic_rep_list." : ".$fic_rep_list[$j]."\n";
		}
		if ($fic_rep_list[$j]!~/^\./ and $fic_rep_list[$j]!~/delete_queries.xml/ and $fic_rep_list[$j]!~/all_queries.xml/ and $fic_rep_list[$j]!~/.svn/) 
		{
			print "Concat   query no ".($j+1)."/".scalar @fic_rep_list." : ".$fic_rep_list[$j]."\n";
			open(F, $source_dir."/".$fic_rep_list[$j]);# || die "Probl�me � l\'ouverture : $!";
			$i = 0;
			while($line = <F>)
			{
				# doit contenir : plmxml_bus:SavedQueryDef
				# doit contenir : plmxml_bus:QueryClause
				# remplacer : <plmxml_bus:SavedQueryDef id="id1" par <plmxml_bus:SavedQueryDef id="id$i"
				# recopier le reste
				if ($line =~ m/\<plmxml_bus:SavedQueryDef/)
				{
					$line =~ s/\"id1"+/\"id$j\"/;
					$line =~ s/nameRef=\"#id.\" //;
					$line =~ s/descriptionTextRef=\"#id.\" //;
					print OUTPUTFILE $line; #On �crit la ligne dans le fichier r�sultat			
				}
				if ($line =~ m/\<Description\>/ )
				{
					print OUTPUTFILE $line; #On �crit la ligne dans le fichier r�sultat			
				}
				if ($line =~ m/\<\/Description\>/ )
				{
					print OUTPUTFILE $line; #On �crit la ligne dans le fichier r�sultat			
				}
				if ($line =~ m/plmxml_bus:QueryClause/ )
				{
					$k=$j+1000;
					$line =~ s/\"id."+/\"id$k\"/;
					print OUTPUTFILE $line; #On �crit la ligne dans le fichier r�sultat			
				}
				# if ($line =~ m/plmxml_bus:Text/ )
				# {
					# $l=$i+2000;
					# $line =~ s/\"id."+/\"id$l\"/;
					# $line =~ s/\<\/plmxml_bus:PLMXMLBusinessTypes\>//;
					# print OUTPUTFILE $line; #On �crit la ligne dans le fichier r�sultat			
				# }
				$i ++;
			}
			$j ++;
			#print "\nNombre de lignes : $fic_rep_list[$j] $i\n";
			close F ;#|| die "Probl�me � la fermeture : $!";
		}
	}

	print OUTPUTFILE "</plmxml_bus:PLMXMLBusinessTypes>\n";

	close OUTPUTFILE;
}
