#!/usr/bin/perl

$procname = substr($0, 1 + rindex($0, '/'));
$conf = "$ENV{'HOME'}/.cuerc";
$workdir = "$ENV{'HOME'}/.junk";
$tmpfile = "${workdir}/cue$$";

open(DEBUG_OUT, ">/tmp/cue.debug") if ($debug);

# read configuration
open(IN, "< $conf");
$f = 0;
while (<IN>) {
	if (/^\%mailcap/) {
		$f++;
		next;
	}
	next if (!$f);
	next if (/^helper:/);
	next if (!/[a-zA-Z0-9]/);
	chomp;
	($type, $cmd, $suffix) = split(/[:;]/);
	$cmd =~ s/^[\s]+//;
	$suffix =~ s/[\s]+//g;
	if (!$suffix) {
		$suffix = substr($type, 1 + index($type, '/'));
	}
	$mailcap{$type} = $cmd;
	$mimetype{$type} = $suffix;
	print DEBUG_OUT "config=[$type] [$cmd] [$suffix]\n" if ($debug);
}
close(IN);

# create a temporary file.
open(OUT, "> $tmpfile");
if (defined $ARGV[0]) {
	open(IN, "< $ARGV[0]");
	while (<IN>) {
		print OUT $_;
	}
	close(IN);
} else {
	while (<STDIN>) {
		print OUT $_;
	}
}
close(OUT);

# decide the mime_type
$mime_type = $ENV{'CUE_MIME_TYPE'};
print DEBUG_OUT "mime_type=[$mime_type]\n" if ($debug);

$cmd0 = '';
foreach $m (keys %mailcap) {
	if ($m eq $mime_type) {
		$ext = $mimetype{$m};
		$cmd0 = $mailcap{$m};
		last;
	}
}
if (! $cmd0) {
	&speculation;
}
if (! $cmd0) {
	print STDERR "$procname: ERROR: command could not be decided.\n";
	exit 1;
}

print DEBUG_OUT "cmd0=[$cmd0]\n" if ($debug);
print DEBUG_OUT "ext=[$ext]\n" if ($debug);

$tmp2file = sprintf "%s%s%s", $tmpfile, $ext ? "." : "", $ext;
rename($tmpfile, $tmp2file);

$cmd = sprintf $cmd0, $tmp2file;
print DEBUG_OUT "cmd=[$cmd]\n" if ($debug);
close(DEBUG_OUT) if ($debug);

system($cmd);
unlink($tmp2file);

exit 0;

sub speculation
{
	open(IN, "< $tmpfile");
	while (<IN>) {
		# HTML
		$sp_html++ if (m@<html>@i);
		$sp_html++ if (m@</html>@i);
		$sp_html++ if (m@<body(\s|>)@i);
		$sp_html++ if (m@</body@i);
		$sp_html++ if (m@<br>@i);
	}
	close(IN);

	if ($sp_html >= 2) {
		$ext = $mimetype{'text/html'};
		$cmd0 = $mailcap{'text/html'};
	} else {
		# last resort
		$ext = $mimetype{'text/plain'};
		$cmd0 = $mailcap{'text/plain'};
	}
	print "speculated [$ext] [$cmd0]\n";
}
