#!/usr/bin/perl -w
use strict;

# upd-execsys
# Copyright (C) 2006  Jeff Arnold <jbarnold@mit.edu>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
#
# See /COPYRIGHT in this repository for more information.

my @dynamic = qw(
 pl
 php
 py
 cgi
 scm
 exe
);

my @static = qw(
 html
 css
 gif
 jpg
 png
 htm
 jpeg
 js
 ico
 xml
 xsl
 tiff
 tif
 tgz
 tar
 jar
 zip
 pdf
 ps
 doc
 xls
 ppt
 swf
 mp3
 mov
 wmv
 mpg
 mpeg
 avi
 il
 JPG
 xhtml
 svg
 xaml
 xap
);

my %map;
open(TYPES, "./mime.types");
while(my $line = <TYPES>) {
	next if($line =~ /^\#/ or $line =~ /^\s*$/);
	my ($type, $exts) = ($line =~ /^(\S*)\s+(.*)$/);
	next if($exts =~ /^\s*$/);
	
	foreach my $ext (split " ", $exts) {
		$map{$ext} = $type;
		$map{uc($ext)} = $type;
	}
}
close(TYPES);

undef $/;
my $regexp = '(.*[\/\#]+\sSTART-AUTOGENERATED:[^!]*!).*\s([\/\#]+\sEND-AUTOGENERATED.*)';

open(CONF, ">./execsys.conf");

foreach my $ext (@dynamic, @static) {
	print CONF <<END
<Files *.$ext>
	SetHandler cgi-script
	Options +ExecCGI
</Files>

END
}
close(CONF);

open(CAT, "./static-cat.c.pre");
$file = <CAT>;
($fstart, $fend) = ($file =~ /$regexp/s);
close(CAT);

open(CAT, ">./static-cat.c");
print CAT $fstart, "\n";
print CAT '#define NEXTS ', scalar(@static), "\n";
print CAT "const char *map[2 * NEXTS] = {\n";
for(my $i = 0; $i < scalar(@static); $i++) {
	my $comma = ( $i < scalar(@static)-1 ? "," : "" );
	print CAT "\t\"$static[$i]\", \"$map{$static[$i]}\"$comma\n";
}
print CAT "};\n";
print CAT $fend;
close(CAT);
