#!/usr/bin/perl -w

use strict;
use vars qw($WEBDIR $SPIN_TEMPLATE $SPIN_INDEX);

use File::Find;
use File::Temp;

# Set directories for cgi scripts and web templates.
$WEBDIR = '/srv/www/tools';

# Location and flags to spin.
$SPIN_TEMPLATE = "/usr/bin/spin -o /usr/share/spin/its-tools.pl";

# This function will, given a spin file, create an html template from it
#  and then filter out pieces we do not want in it.
sub spin_file {
    my ($fname) = @_;

    # Spin out the file.
    my $outfile = $fname;
    if ($fname =~ m#/index\.th$#) {
        $outfile =~ s#\.th$#.html#;
    } elsif ($fname =~ m#\btracker-stats\b#) {
        $outfile =~ s#\.th$#.tmpl#;
    } else {
        $outfile =~ s#\.th$#.tmpl#;
    }
    print "Spinning $fname\n";
    my $retval = system ($SPIN_TEMPLATE . " $fname $outfile");

    # Clean up the output to make sure that includes on the index docs
    #  go to the correct local destination and not the WWW destination.
    if ($fname =~ m#/index\.th$#) {
        local($^I, @ARGV) = ('', ($outfile));
        while (<>) {
            s%="/dept/its/docs/%="/%;
            print;
        }
    }

}

# Used by File::Find to discover the files we wish to spin into HTML.
sub wanted {
    /^.*\.th\z/s && spin_file ($File::Find::name);
}

# Check for a directory sent us to start our search in.
my ($dir) = @ARGV;
if (defined $dir && $dir) {
    File::Find::find ({wanted => \&wanted}, $dir);
} else {
    warn "No directory specified\n";
    exit(1);
}

exit(0);
