#!/usr/bin/perl
use strict;
use warnings;
use File::Next;
use Getopt::Long;

my $templatefile = <<'END_TEMPLATE';
<html><body bgcolor="#FFFFFF"></body></html>
END_TEMPLATE
my $file = "";
my $Confirm = "yes";
my $VERSION = "1.0.0";
my $DebugMode;
my $NoConfirm;
my $ShowHelp;

print "createindex - index.html file creator v$VERSION\n";
print "===============================================\n";

GetOptions ("debug" => \$DebugMode,
            "help"   => \$ShowHelp,
            "noconfirm"  => \$NoConfirm)
or die("Error in command line arguments\n");

sub DisplayHelp
{
	print "Valid options are:\n";
	print "\t--noconfirm\t- Don't confirm each creation\n";
	print "\t--help\t\t- displays this message\n";
	print "\t--debug\t\t- turns on debug mode\n";
	exit 0;
}

if ($NoConfirm)
{
	$Confirm = "no";
}
if ($ShowHelp)
{
	DisplayHelp();
}

sub PrintDebugCommand
{
        if (! $DebugMode)
        {
                return;
        }
        my $PassedString = shift;
        print "$PassedString\n";
	#print "Press Enter To Run This:";
	#my $entered = <STDIN>;
}

sub CreateIndex
{
	my $OutputFile = "$file/index.html";
	if (-f $OutputFile)
	{
		print "$OutputFile already exists - skipping\n";
		return;
	}
	if ($Confirm eq "yes")
	{
		print "About to create $OutputFile - Confirm: Y/n/q: ";
		my $entered = <STDIN>;
		chop($entered);
		if ($entered eq "n")
		{
			return;
		}
		if ($entered eq "q")
		{
			print "Quiting...\n";
			exit 0;
		}
	}
	open(FH, '>', $OutputFile) or die $!;
	print FH "$templatefile";
	close(FH);
}

if ($Confirm eq "no")
{
	print "No comfirmations\n";
}

my $iter = File::Next::dirs( '.' );
while ( defined ( $file = $iter->() ) )
{
	if (substr($file, 0, 1) eq ".")
	{
		next;
	}
	if (index($file, ".git") != -1)
	{
		PrintDebugCommand("$file contains .git");
		next;
	}
	PrintDebugCommand("saw $file");
	CreateIndex();
}

exit 0;
