use strict;
use warnings;
use File::Find;
use File::Path;
use File::Spec;

$| = 1;

print "checking for mlpod2html... ";
my $devnull = File::Spec->devnull();
my $mlpod2html = `which mlpod2html 2>$devnull`;
if ($mlpod2html) {
	chomp $mlpod2html;
	print "$mlpod2html\n";
}
else {
	print "no\n";
}

my @pod; # [pm, html]

find({
    wanted => sub {
	my $fpath = $_;
	$fpath =~ m!\.pm$! or return;

	my @fname = File::Spec->splitdir($fpath);
	shift @fname; # ..を消す
	shift @fname; # libを消す
	my $fname = pop @fname; # ファイル名を消す
	$fname =~ s/\.pm$/.html/;

	if (@fname) {
	    mkpath([File::Spec->catdir(@fname)]);
	}

	push @pod, [
	    $fpath,
	    File::Spec->catdir(@fname, $fname),
	   ];
    },
    no_chdir => 1,
}, '../lib');
push(@pod,
	 ['../ext/Tripletail-HtmlFilter/HtmlFilter.pm' => 'Tripletail/HtmlFilter.html'],
	 ['../ext/Tripletail-SMIME/SMIME.pm'           => 'Tripletail/SMIME.html'],
	 ['policy.pod', 'policy.html'],
	 ['security.pod', 'security.html'],
	 ['tips.pod', 'tips.html'],
);

open my $fh, '>', 'Makefile' or die;
print $fh "# This makefile has been generated by Makefile.PL.\n";
print $fh "# Do not edit by hand.\n";
print $fh "\n";
print $fh "all: doc\n";
print $fh "\n";
foreach my $pod (@pod) {
    print $fh "$pod->[1]: $pod->[0]\n";
    print $fh "\t$mlpod2html \$< -o \$\@ --poddir=. --missing-dir=. --css=style.css\n";
    print $fh "\n";
}
if ($mlpod2html) {
	print $fh "doc: ".join(' ', map {$_->[1]} @pod)."\n";
}
else {
	print $fh "doc:\n";
	print $fh "\t\@echo Note: html doc will not be generated for lack of mlpod2html.\n"
}
print $fh "\n";
print $fh "test: \n";
print $fh "\n";
print $fh "clean: \n";
print $fh "\trm -f Makefile\n";
if ($mlpod2html) {
	foreach my $pod (@pod) {
		print $fh "\trm -f $pod->[1]\n";
	}
}
print $fh "\n";
print $fh "touch:\n";
print $fh "\ttouch -t 01010000 \`find -name '*.html'\`\n";
print $fh "rebuild: touch all\n";
print $fh "\n";
print $fh ".PHONY: all doc test clean\n";
close $fh;
