#!/perl -w
# NAME: listrepodirs.pl
# AIM: Given an imput foldeer. make a list of all FRONTPAGE folders
# I use this list to avoid ZIPPING these folders, when doing a zip backup ...
# 2010/01/31  - geoff mclane - http://geoffair.net/mperl/
use strict;
use warnings;
use File::Basename;
use File::stat; # to get the file date
unshift(@INC, 'C:/GTools/perl');
require 'logfile.pl' or die "Unable to load logfile.pl ...\n";
# log file stuff
my ($LF);
my $pgmname = $0;
if ($pgmname =~ /\w{1}:\\.*/) {
    my @tmpsp = split(/\\/,$pgmname);
    $pgmname = $tmpsp[-1];
}
my $perl_root = 'C:\GTools\perl';
my $outfile = $perl_root.'\temp.'.$pgmname.'.txt';
my $templist = $perl_root.'\temprepos.txt';
my $tempbat = $perl_root.'\tempdelrepos.bat';

open_log($outfile);
### prt( "$0 ... Hello, World ...\n" );
my $in_folder = '';
my $def_folder = 'C:\FGCVS\PLIB';
#my $def_folder = 'C:\FG\32\data';
#my $def_folder = 'C:\HOMEPAGE';
my $bat_file = '';
$in_folder = shift @ARGV || $def_folder;

my $load_log = 0;
my @repofolders = qw( CVS .svn .git );
my @folderlist = ();
my %reposfound = ();
my $fndcnt = 0;
my $filcnt = 0;
my $dircnt = 0;
my $file = '';
my $total_size = 0;
my $total_cnt  = 0;
my $block_size = 4096;
my $total_blocks = 0;
my $start_time = time();
prt( "Processing folder $in_folder ...\n" );

sub b2ks2($) {
   my ($d) = @_;
	my $oss;
	my $kss;
	my $lg = 0;
	my $ks = ($d / 1024); #// get Ks
	my $div = 1;
   if( $ks < 1024 ) {
      $div = 1;
      $oss = "KB";
   } elsif ( $ks < (1024*1024) ) {
	  $div = 1024;
      $oss = "MB";
   } elsif ( $ks < (1024*1024*1024) ) {
      $div = 1024 * 1024;
      $oss = "GB";
   } else {
      $div = 1024 * 1204 * 1240;
      $oss = "TB";
   }
   $kss = $ks / $div;
   $kss += 0.05;
   $kss *= 10;
   $lg = int($kss);
   $kss = $lg / 10;
   $kss .= '.0' if (!($kss =~ /\./));
   ###return( ($lg / 10) . " " . $oss );
   return "$kss$oss";
}

get_folder_list($in_folder);
$fndcnt = scalar @folderlist;
prt( "Found $fndcnt REPOSITORY folders ... in $dircnt directories, $filcnt files (in ".elapsed_seconds()." secs)\n" );
foreach $file (keys %reposfound) {
    my $cnt = $reposfound{$file};
    prt( " $cnt of type [$file]\n" );
}
if (length($templist)) {
    if (open OF, ">$templist") {
        foreach $file (@folderlist) {
            print OF "$file\n";
        }
        close OF;
        prt("List written to [$templist] file...\n");
        if (length($tempbat)) {
            if (open OF, ">$tempbat") {
                print OF get_batch_text($templist);
                close OF;
                prt("Batch file written [$tempbat]... to do delete...\n");
                $bat_file = $tempbat;
            } else {
                prt("WARNING: Unable to create [$tempbat] file!\n");
            }
        }
    } else {
        prt("WARNING: Unable to create [$templist] file!\n");
    }
} else {
    foreach $file (@folderlist) {
        prt( "$file\n" );
    }
}

prt( "Printed $fndcnt REPOSITORY folders... containing $total_cnt files, $total_size bytes (~".b2ks2($total_blocks * $block_size).") in ".elapsed_seconds()." secs.\n" );
if (length($bat_file)) {
    prt("Use [$bat_file] to do the delete...\n");
}
close_log($outfile,$load_log);
exit(0);

######################################
sub elapsed_seconds {
    my $tm = time();
    return ($tm - $start_time);
}

sub is_repo_folder {
    my ($fdr) = shift;
    my ($tst);
    foreach $tst (@repofolders) {
        return 1 if ($tst eq $fdr);
    }
    return 0;
}

sub contains_repo_folder {
    my ($dir) = shift;
    $dir =~ s/\\/\//g;
    my @arr = split("/",$dir);
    my ($tst);
    foreach $tst (@arr) {
        return 1 if (is_repo_folder($tst));
    }
    return 0;
}

sub get_folder_list {
    my ($inf) = shift;
    my ($itm, $ff, $sb, $sz, $blks);
    my @fldrs = ();
    my $isrep = contains_repo_folder($inf);
	if ( opendir( DIR, $inf ) ) {
		my @files = readdir(DIR);
		closedir DIR;
		foreach $itm (@files) {
			next if (($itm eq '.') || ($itm eq '..'));
			$ff = $inf . "\\" . $itm;
			if (-d $ff) {
                if ( is_repo_folder($itm) ) {
                    push(@folderlist, $ff);
                    if (defined $reposfound{$itm}) {
                        $reposfound{$itm}++;
                    } else {
                        $reposfound{$itm} = 1;
                    }
                }
                push(@fldrs,$ff);
                $dircnt++;
                if (($dircnt % 100) == 0) {
                    prt( "Found ".scalar @folderlist." REPOSITORY folders ... in $dircnt directories, $filcnt files ... (".elapsed_seconds()." secs)\n" );
                }
            } else {
                if ($isrep) {
                    $total_cnt++;
                    if ($sb = stat($ff)) {
                        $sz = $sb->size;
                        $total_size += $sz;
                        $blks = int($sz / $block_size);
                        $blks++ if ($sz - ($blks * $block_size));
                        $blks++ if ($blks == 0);
                        $total_blocks += $blks;
                    }
                }
                $filcnt++;
            }
        }
        foreach $itm (@fldrs) {
            get_folder_list($itm);
        }
    } else {
        prt( "ERROR: Failed to OPEN $inf ...\n" );
    }
}

sub get_batch_text {
    my ($out) = @_;
    my $bt = <<EOF;
\@setlocal
\@echo Batch file to delete repo directories, per the file list in
\@set TEMP1=$out
\@echo file [%TEMP1%]...
\@if NOT EXIST %TEMP1% goto ERR1
\@set TEMPCNT=0
\@for /F "tokens=*" %%i in (%TEMP1%) do @(call :GETCNT %%i)
\@echo Count in file is %TEMPCNT%
\@echo *** CONTINUE? *** Ctrl+C to abort...
\@pause
\@echo Count in file is %TEMPCNT%
\@echo *** ARE YOU REALLY SURE? *** Ctrl+C to abort...
\@pause
\@set TEMPTOT=%TEMPCNT%
\@set TEMPCNT=0
\@for /F "tokens=*" %%i in (%TEMP1%) do @(call :DODEL %%i)

\@goto END

:GETCNT
\@if "%1x" == "x" goto :EOF
\@if NOT EXIST "%1\." goto :FAIL
\@set /A TEMPCNT+=1
\@goto :EOF

:DODEL
\@if "%1x" == "x" goto :EOF
\@if NOT EXIST "%1\." goto :FAIL
\@set /A TEMPCNT+=1
\@echo Doing %TEMPCNT% of %TEMPTOT%
\@xdelete "%1" -dfrm "-NO-confirmation-please=1" -v0
\@goto :EOF

:FAIL
\@echo ERROR: Can NOT locate directory [%TEMP1%]..
\@pause
\@goto :EOF

:ERR1
\@echo ERROR: Can NOT locate file [%TEMP1%]... Aborting...
\@goto END

:END
\@endlocal
EOF
    return $bt;
}

# eof - listrepodirs.pl
