#!/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
 scm
);

my @static = qw(
 html
 css
 gif
 jpg
 png
 htm
 jpeg
 js
 ico
 xml
 xsl
 tiff
 tif
 tgz
 tar
 jar
 pdf
 ps
 doc
 xls
 ppt
 swf
 mp3
);

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;
	}
}
close(TYPES);

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

# Read existing binfmt file

open(BINFMT, "./execsys-binfmt.pre");
my $file = <BINFMT>;
my ($fstart, $fend) = ($file =~ /$regexp/s);
close(BINFMT);

# Write new binfmt file

open(BINFMT, ">./execsys-binfmt");
print BINFMT $fstart, "\n";

foreach my $ext (@dynamic) {
  my $path = $ENV{"${ext}_path"};
  print BINFMT "echo \":${ext}:E::${ext}::${path}:\" > /proc/sys/fs/binfmt_misc/register\n" if($path);
}

foreach my $ext (@static) {
	print BINFMT "echo \":${ext}:E::${ext}::$ENV{syscat_path}:\" > /proc/sys/fs/binfmt_misc/register\n";
}
print BINFMT $fend;
close(BINFMT);

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, "./staticsys-cat.c.pre");
$file = <CAT>;
($fstart, $fend) = ($file =~ /$regexp/s);
close(CAT);

open(CAT, ">./staticsys-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);
