#!/usr/bin/perl

use warnings;
use strict;
#use re 'debug';

open my $fh, "<magic.mime" or die;
my @lines = <$fh>;
close $fh;

my @registered_types = `./get_iana_types.pl`;
my %content_types = ();
foreach my $type (@registered_types)
{
	chomp $type;
	my ($type, $subtype) = split /\//, $type;
	push @{$content_types{$type}}, $subtype;
}

foreach my $line (@lines)
{
	if ($line =~ /^#/) { next; }
	if ($line =~ /^\s*$/) { next; }
	# MIME type is in the 4th tabs-separated field
	# Ugh, some lines have fields separated by spaces.  Worst,
	# some are separated by only one space, while a space can occur
	# in the magic signature, as long as it is preceded by a
	# backslash!

	my $mime = '';
#	if ($line =~ /^[^\t]+(?:\t+|[\t\s]{2,})[^\t]+(?:\t+|[\t\s]{2,})[^\t]+(?:\t+|[\t\s]{2,})([^\t]+?)(?:\t.*)?$/) {
	if ($line =~ /^(?:[^\s]|(?<=\\)\s)+\s+(?:[^\s]|(?<=\\)\s)+\s+(?:[^\s]|(?<=\\)\s)+\s+((?:[^\s]|(?<=\\)\s)+)(?:\s+.*)?$/) {
		$mime = $1;
		#print $line;
		#print $mime."\n";
	}
	else {
		#print STDERR "Non-matched line: $line";
		next;
	}

	$mime =~ /^(.*)\/(.*)$/;
	my $type = $1;
	my $subtype = $2;
	my $match = 0;

	# If not x- subtype, make sure it is registered
	if ($subtype !~ /^x-/) {
		my $lower = '';
		foreach my $reg_subtype (@{$content_types{$type}})
		{
			if ($subtype eq $reg_subtype) { $match = 1; }
			if (lc($subtype) eq lc($reg_subtype)) { $lower = $reg_subtype; }
		}
		if (!$match) {
			print STDERR "$mime is not a registered type; use $type/x-$subtype instead!\n";
			if ($lower) {
				print STDERR "It is possible that $type/$lower is what you meant.\n";
			}
		}
	}
	else {
		my $lower = '';
		# make sure there is no registered type
		$subtype =~ s/^x-//;
		foreach my $reg_subtype (@{$content_types{$type}})
		{
			if ($subtype eq $reg_subtype) { $match = 1; }
			if (lc($subtype) eq lc($reg_subtype)) { $lower = $reg_subtype; }
		}
		if ($match) {
			print STDERR "$mime is prefixed with x-, but looks like a registered type; use $type/$subtype instead.\n";
		}
		elsif ($lower) {
			print STDERR "Did you mean $type/$lower instead of $mime ?\n";
		}
	}

}
