#! /usr/bin/perl
#############################################################################
# 
#############################################################################
#  
#   GLOBAL VARIABLES {
#
#############################################################################
 
 
$dirname = ".";
$subdir = "true";

$replace=$ARGV[0];
$by=$ARGV[1];
$extention=$ARGV[2];
$rec=$ARGV[3];
$DONTTOUCHBACKUPS=1;
   
if (($replace eq "") || ($by eq "") || ($extention eq "" ) || ($extention eq "-r" ) ) {
    print"\n USAGE: \n\tabsolute.pl   current_string  replace_by_string extension [-r]. You may select  ALL for extention\n\n";
    exit();
}
# if (  $rec eq "-r")
# {$subdir="true";}

print "Replacing $replace with $by \n";
if ($DONTTOUCHBACKUPS) {
    print "SKIP  *~ \n" ;
    print "SKIP  *.default\n";
    print "SKIP  *.tar\n";
    print "SKIP  *.gz\n";
    print "SKIP  *.jar\n";
}
    
handledir($dirname,0);





sub handledir() {
local($dir,$l)=@_;
print "$dir\n";
opendir(DIR, $dir) || die "no dir .";
foreach $fn ( readdir(DIR)) {
	#if ($l >= 5) {continue;}

	if ($fn eq ".") { next;}
	elsif ($fn eq "..") { next;}
	

	$fn=$dir."/".$fn;

	if (-d $fn) {
	        if ( $x =readlink($fn) ) {
		    print "SKIPPING THE LINK at $fn --> $x \n";
		    next;
		}
		$l+=1;
		if ($subdir eq "true") {
		    handledir($fn,$l);
		}
		$l-=1;
	} else {
	        if ( $x =readlink($fn) ) {
		    print "SKIPPING THE LINK at $fn --> $x \n";
		    next;
		}

	    if ($extention eq "ALL" ) {;}
	    elsif (!($fn =~ /.$extention\b/ )){next;}
	    if ($DONTTOUCHBACKUPS) {
		# print "$fn ? ";
		if ( ($fn =~ /~/ )){ next;}
		elsif ( ($fn =~ /\.default\b/ )){ next;}
		elsif ( ($fn =~ /\.jar\b/ )){next;}
		elsif ( ($fn =~ /\.tar\b/ )){next;}
		elsif ( ($fn =~ /\.gz\b/ )){next;}
	    }
	    if (  searchfile($fn) )
	     {handlefile($fn,$l);	}
	}
}
}

sub searchfile(){
    local($file)=@_;
    open(IN, "<$file"); 
    while (<IN>) {
	$line=$_;
	if ($line=~ /$replace/) { close(IN); print "$file "; return 1;}
    }
    close(IN);
    #print "$file CLEAR\n";
    return 0;
}




sub handlefile(){
local($file,$l)=@_;

print "Return without handling \n";return; 
 open(IN, "<$file"); 
$of=$file."___";
 open(OUT, ">$of"); 

	 while (<IN>) {
		$line=$_;
		$line=~ s/$replace/$by/g;
	 	print OUT $line;
	}
 close(IN);
 close(OUT);

 rename($of,$file);
 print " OK \n";

}


