#!/usr/bin/perl -w

use strict;
use Switch;

my $outputFileName = "scripts.tex";
my @ignoreFilePatterns=('__init__\.py$','lib/pstat\.py$','lib/stats\.py$','.*\.csv$','.*\.lisp$');
my $codePath = "scripts/";
my @systems = ("lib","verify-xomo","casestudies-csv2nova","casestudies-star2nova");
my $licenceLineLength = 0;

open OFILE,">",$outputFileName or die $!;
print OFILE "\\lstset{tabsize=2,frame=single,basicstyle=\\tiny,lineskip=3pt}\n";

sub checkFilePath {
    my ($filePath) = @_;
    for my $ignoreFilePattern (@ignoreFilePatterns) {
	if($filePath=~ m/($ignoreFilePattern)/) {
	    return 0;
	}
    }
    return 1;
}

sub determineLanguage {
    my ($filePath) = @_;
    my $extension = $filePath;
    $extension =~ s/.*\.([^.]+)/$1/;
    switch ($extension) {
	case "py" { return "python" }
	case "sh" { return "bash" }
	else { return ""; }
    }
}

sub printListingCommand {
    my ($filePath) = @_;
    my $title = $filePath;
    $title =~ s/($codePath)(.*)/$2/;
    my $language = determineLanguage($filePath);
    my $languageDef = $language ? "language=$language," : "";
    print OFILE "\\lstinputlisting[${languageDef}title=$title,firstline=$licenceLineLength]{$filePath}\n";
}

sub printSystemHeading {
   my($system) = @_;
   print OFILE "\\section{$system}\\label{scripts-src-$system}\n";
}

sub processDirectory {
    my($path) = @_;
    my @directories = ();
    for my $file (<$path/*>) {
	if (-d $file) {
	    push(@directories,$file);
	} else {
	    if (checkFilePath($file)) {
		printListingCommand($file);
	    }
	}
    }
    for my $dir (@directories) {
	processDirectory($dir)
    }

}

sub printSystemFooter {
   my($system) = @_;
   print OFILE "\\newpage\n";
}

for my $system (@systems) {
    printSystemHeading($system);
    processDirectory($codePath . $system);
    printSystemFooter($system);
}

close OFILE;
