#!/usr/bin/env perl
#
# Wadinfo builder, rewritten in perl :)
#
# By Simon Howard (fraggle)
#
# You may consider this GPLed.

use strict;

my $dummy = 0;

sub findfile {
	my ($section, $name) = @_;

	my $filename = "$section/" . lc($name) . ".*";
	my @list = glob($filename);
	
	return undef if scalar @list <= 0;

	return $list[0];
}

for (my $i=0; $i<scalar @ARGV; ++$i) {
	$_ = $ARGV[$i];

	if ($_ eq '-dummy') {
		$dummy = 1;
	} 
}

print "; This file is automatically generated, do not edit it directly!\n\n";

my $section = "";

while (<STDIN>) {
	chomp;

	# remove comments

	s/[\#\;].*$//;

	# check for empty lines and comments

	# sections

	if(/\[.*\]/) {

		# extract section name

		$section = $_;
		$section =~ s/.*\[//;
		$section =~ s/\].*//;

		# catch [texture1] and [texture2] which are in 
		# textures/

		$section = "textures"
	 		if $section eq "texture1" ||
			   $section eq "texture2";

	} elsif (/^\s*(\S+)[^\=]*(\s*\=\s*(\S+))?/) {
		
        my ($resname, $override) = ($1, $3);
           
        $resname = lc($resname);

        # allow "=foo" to override the filename used

		my $filename;

        if ($override) {
            $filename = findfile($section, $override);
        } else {
            $filename = findfile($section, $resname);
        }

		if (!$filename) {
			if ($dummy) {

                # this hasnt been submitted yet - use a dummy lump
                # instead

				if ($resname =~ /^DEMO/i) {
					$_ = "$resname = fakedemo";
				} else {
					$_ = "$resname = dummy";
				}
			} else {
                # disabled entries are commented out

				$_ = ";$_";
			}
		}
	}

	print $_ . "\n";
}
