#!/usr/bin/perl
use strict;
use warnings;
my $copyright = <<'EOF';
/* Copyright (C) 2012,2013,2015 Olly Betts
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */
EOF

use Tokeniseise;

my $srcdir = shift @ARGV;

-d 'docs/inc' or mkdir 'docs/inc' or die $!;

my $hdr = Tokeniseise->new('mimemap.h', 'Map extension to MIME Content-Type', $copyright, 'OMEGA_INCLUDED_MIMEMAP_H', 'mime_type');
$hdr->append('static const char * const default_mime_map[] = {');
my $max_ext_len = 0;
my %seen;
my @ignored;
while (<STDIN>) {
    s/#.*//;
    next if /^\s*$/;
    my ($ext, $mimetype) = split /\s+/;
    my $enum = uc $mimetype;
    $enum =~ s![-+/.]!_!g;
    $hdr->add($ext, $enum);
    $max_ext_len = length($ext) if length($ext) > $max_ext_len;
    if (!exists $seen{$mimetype}) {
	$hdr->append("    \"$mimetype\",");
	++$seen{$mimetype};
    }
    if ($mimetype eq 'ignore') {
	push @ignored, $ext;
    }
}
$hdr->append('};');
$hdr->append('');
$hdr->append("const size_t MAX_BUILTIN_MIMEMAP_EXTENSION_LEN = $max_ext_len;");

$hdr->write();

open IGNORED, '>', 'docs/inc/ignored.rst' or die $!;
foreach my $ext (sort @ignored) {
    print IGNORED "   - $ext\n";
}
close IGNORED or die $!;

open MIMETYPES, '>', 'docs/inc/mimetypes.rst' or die $!;
sub mimetype_order {
    my ($a, $b) = @_;
    $a =~ s!^text/!0/!;
    $a =~ s!^application/!1/!;
    $a =~ s!^image/!2/!;
    $b =~ s!^text/!0/!;
    $b =~ s!^application/!1/!;
    $b =~ s!^image/!2/!;
    return $a cmp $b;
}
# Include 'skip' in the list even if it isn't used by default.
++$seen{'skip'};
foreach my $mimetype (sort {mimetype_order($a, $b)} keys %seen) {
    if ($mimetype eq 'ignore') {
	$mimetype .= ' (magic token to tell omindex to quietly ignore such files)';
    }
    if ($mimetype eq 'skip') {
	$mimetype .= ' (magic token to tell omindex to skip such files)';
    }
    print MIMETYPES "   - $mimetype\n";
}
close MIMETYPES or die $!;
