#!/usr/local/bin/perl
use IO;
       
        $agora_dir = "agora";
        $ext = "php";
        $newext = "phtml";

        sub process_file {
                my $file = $_[0];
                #global $ext, $newext;
       

                #$fext = strrchr ($file, ".");
                #($dumb, $fext) = split('.', $file);
                $fext = substr($file, rindex($file, "."), length($file)-rindex($file, "."));
                if ( ($fext ne ".$ext") && ($fext ne ".inc") ) {
                        return FALSE;
                }
                $len = length ($file) - length ($fext);
                $new_file = substr ($file, 0, $len) . ".$newext";

                my (@new_file_lines);
                my $fdin = IO::File;
                if ( open ($fdin, "<$file") ) {
                        while (<$fdin>) {      
                                $content = $_;
                                if ($content =~ /^\<\?php/i) {
                                        push(@new_file_lines, $content);
                                        next;                           
                                }            
                                $content =~ s/(.)$ext/$1$newext/g;
                                if ($content =~ /\<\?phtml/i) {
                                        $content =~ s/phtml/php/;
                                }            
                                if ($content =~ /ldap\.php/i) {
                                        $content =~ s/php/phtml/;
                                }            
                                push(@new_file_lines, $content);
                        }
                        close ($fdin);
                } else {
                        print "could not open file: $file \n";
                        return FALSE;
                }
                 
                #$file_out = ($fext == ".inc") ? $file : $new_file;
                if ($fext eq ".inc") {
                        $file_out = $file;
		} else {
			$file_out = $new_file;
		}

		my $fdout = IO::File;
		if (open($fdout, ">$file_out")) {
			foreach $out (@new_file_lines) {
				print $fdout $out;
			}
			close $fdout;
		} else {
			print "could not open file: $file_out\n";
			return FALSE;
		}

		if ($file_out ne $file) {
			unlink ($file);
		}

		print "  $file -> $file_out\n";
	}

sub browse_dir {
	my $path = $_[0];
	#global $ext;

	my $dir = IO::Dir->new($path);
	opendir ($dir, $path);
	while ($entry = readdir $dir) {
		if ( ($entry ne '.') && ($entry ne '..') ) {
			if ( -d "$path/$entry") {
				print "    $entry\n";
				browse_dir ("$path/$entry");
			} else {
				process_file ("$path/$entry");
			}
		}
	}
	closedir $dir;
}

print "Changing extensions for PHP scripts from $ext to $newext\n\n";
browse_dir("$agora_dir");

