#!/usr/bin/perl

# possible modules to use
use Getopt::Long;

# Benchmarking variables
my $startime = time();
my $totalcount = 0;
my $connections = 0;

# Options
my $dir = '/home/koha/gitosis-admin/am123/C4/';
my $verbose;
my $outfile;
my $delimiter = ',';

GetOptions(
  'o|output:s' => \$outfile,
  'd|delimiter:s' => \$delimiter,
  'v' => \$verbose
);

# take in a textual delimiter and change to symbol
if ($delimiter eq 'pipe') {
   $delimiter = '|';
} elsif ($delimiter eq 'semicolon') {
   $delimiter = ';';
} elsif ($delimiter eq 'colon') {   
   $delimiter = ':';
} elsif ($delimiter eq 'tab') {
   $delimiter = "\t";
} elsif ($delimiter eq 'space') {
   $delimiter = ' ';
}

# output log or STDOUT
if (defined $outfile) {
   open (OUT, ">$outfile") || die ("Cannot open output file");
} else {
   open(OUT, ">&STDOUT") || die ("Couldn't duplicate STDOUT: $!");
}

print "Reading $dir, printing to $outfile, delimiting with '$delimiter'\n" if (defined $verbose);

print OUT "digraph kohaC4dep {\n";
process_dir ($dir);
print OUT "}";

# Benchmarking
my $endtime = time();
my $time = $endtime-$startime;
my $averagetime = 0;
unless ($time == 0) {$averagetime = $totalcount / $time;}
print "Total $totalcount files (nodes) touched ($connections edges) in $time seconds\n";
printf "Average time per record: $averagetime%.6f seconds\n" if (defined $verbose); 




# Accepts one argument: the full path to a directory.
# Returns: nothing.
sub process_dir {
    my $path = shift;

    # Open the directory.
    opendir (DIR, $path)
        or die "Unable to open $path: $!";

    # Read in the files.
    # You will not generally want to process the '.' and '..' files,
    # so we will use grep() to take them out.
    # See any basic Unix filesystem tutorial for an explanation of them.
    my @files = grep { !/^\.{1,2}$/ } readdir (DIR);

    # Close the directory.
    closedir (DIR);

    # At this point you will have a list of filenames
    #  without full paths ('filename' rather than
    #  '/home/count0/filename', for example)
    # You will probably have a much easier time if you make
    #  sure all of these files include the full path,
    #  so here we will use map() to tack it on.
    #  (note that this could also be chained with the grep
    #   mentioned above, during the readdir() ).
    @files = map { $path . '/' . $_ } @files;

    for (@files) {

        # If the file is a directory
        if (-d $_) {
            # Here is where we recurse.
            # This makes a new call to process_files()
            # using a new directory we just found.
            process_dir ($_);

        # If it isn't a directory, lets just do some
        # processing on it.
        } else { 
            process_file($_);
            $totalcount++;
        }
    }
}


sub process_file {
   my $filename = shift;
   unless ($filename =~ m/\.pm$/){ return;}
   open(FILE, "$filename") || warn ("Cannot open input file");
   my $modulename = $filename;
   if ($modulename =~ m/C4\/(.*).pm/) {
      $modulename = '"C4::'.$1.'"';
      $modulename =~ s/\//::/g;
   }

   while (<FILE>) {
      if (m/^use C4::([\w:\-]*)\s*.*;/){
         print OUT $modulename, " -> ", '"C4::', $1, '" [rank=same]', "\n";
         $connections++;
      } elsif (m/^BEGIN/) { return;}
   }
   $totalcount++;
}
