#!/usr/bin/perl
#create an epub file with Pandoc
#epubmaker Astounding\ Scripts.html "42 Astoundingly Useful Scripts and Automations for the Macintosh" 9780463422823
#epubmaker --kindle Astounding\ Scripts.html "42 Astoundingly Useful Scripts and Automations for the Macintosh" 9780463422823
#epubmaker Dream\ of\ Poor\ Bazin.html "The Dream of Poor Bazin" 9781005613440
#epubmaker --kindle Dream\ of\ Poor\ Bazin.html "The Dream of Poor Bazin" 9781005613440
#epubmaker "The Barefoot Gourmet.html" "The Barefoot Gourmet" 000000000 "Carl Randall"
#epubmaker "Franklin Golden Syrup Recipes.html" "Franklin Golden Syrup Recipes" 000000000 "Franklin Sugar Refining Company"
# Jerry Stratton astoundingscripts.com

use File::Copy;
use DateTime;

$HOME = "$ENV{'HOME'}/bin";

if ($ARGV[0] eq '--kindle') {
	shift;
	$format = '--kindle';
	$contentFile = 'kindle.html';
} else {
	$format = '';
	$contentFile = 'content.html';
}
$htmlFile = shift;
$title = shift;
$isbn = shift;
$author = shift;
$author = 'Jerry Stratton' if $author eq '';

$filename = $htmlFile;
$filename =~ s/\.html$//;
$interimEPUB = 'interim.epub';
$customImages = 'eImages';
if ($format eq '--kindle') {
	$epubFile = "$filename (kindle).epub";
} else {
	$epubFile = "$filename.epub";
}
$workshop = 'epubWorkshop';
$chapterFolder = "$workshop/EPUB/text";
$imageFolder = "images";

die("No such file $htmlFile") if !-f $htmlFile;
die("Title required") if !$title;
die("ISBN required") if !$isbn;
die("No metadata.xml") if !-f 'metadata.xml';
verifyMetadata();

print "Converting Nisus HTML to Pandoc HTML\n";
print `$HOME/epubber $format "$htmlFile" > $contentFile`;

#copy in any images designed solely for the ePub/online version
if (-d $customImages) {
	print "Copying custom images into ePub.\n";
	opendir($images, $customImages) or die("Cannot open $customImages: $!");
	foreach $customImage (readdir($images)) {
		next if $customImage =~ /^\.\.?$/;
		next if $customImage eq '.DS_Store';
		next if $customImage != /\.png$/;
		$sourceImage = "$customImages/$customImage";
		$destinationImage = "$imageFolder/$customImage";
		if (!-f $destinationImage) {
			print "There is no $customImage at $destinationImage to replace.\n";
		} else {
			print "\t$sourceImage\n";
			copy($sourceImage, $destinationImage) or die "Copy of $sourceImage to $destinationImage failed: $!";
		}
	}
}

print "Creating Pandoc epub file\n";
print `pandoc --from html --to epub -o "$interimEPUB" $contentFile --css epub.css --tab-stop 2 --epub-cover-image cover.png --epub-metadata metadata.xml --metadata author="$author" --metadata title="$title" --metadata identifier="$isbn"`;

print `rm -r $workshop`;

print `mkdir -p $workshop`;

print `unzip -q "$interimEPUB" -d $workshop`;

#fix the footnotes
print "Fixing footnotes\n";
opendir($chapters, $chapterFolder) or die("Cannot open $chapterFolder: $!");
foreach $chapter (readdir($chapters)) {
	next if $chapter !~ /^ch[0-9]+\.xhtml$/;
	print "\t$chapter\n";
	$chapterFile = "$chapterFolder/$chapter";
	open $chapterText, '<', $chapterFile or die("Cannot open $chapterFile: $!");
	$newText = '';
	$inAside = 0;
	$title = '';
	while (<$chapterText>) {
		#fix asides
		if ($inAside && m!^</div>!) {
			s/div/aside/;
			$inAside = 0;
		} elsif (/<div id="[^ ]+" type="footnote">/) {
			$inAside = 1;
			s/<div id="([^ ]+)" type="footnote">/<aside id="$1" epub:type="footnote">/;
		}

		#fix links to asides
		s!<sup><a href="ch[0-9]+\.xhtml(#[^ ]+)">\*</a></sup>!<sup><a href="$1" epub:type="noteref">*</a></sup>!g;

		#find title of chapter
		$title = $1 if m!<h1>(.*)</h1>!;

		#save text
		$newText .= $_;
	}
	close $chapterText;

	#set chapter title
	$chapterText =~ s!<title>[^>]+</title>!<title>$title</title>! if $title;

	open $chapterText, '>', $chapterFile or die("Cannot open $chapterFile for saving: $!");
	print $chapterText $newText;
	close $chapterText;
}

print "Creating $epubFile\n";

unlink $epubFile;
chdir $workshop;
#--no-extra = do not save extra file attributes of macOS
print `zip --quiet -X --recurse-paths "../$epubFile" mimetype EPUB META-INF`;
chdir '..';

print "Converted $htmlFile to $epubFile\n";

# verify ePub
print `epubcheck "$epubFile"`;

sub verifyMetadata {
	my $metadata = `/bin/cat metadata.xml`;
	$metadata =~ m/<dc:date opf:event="publication">([0-9]+)-([0-9]+)-([0-9]+)/;
	my $publishDate = DateTime->new(day=>$3, month=>$2, year=>$1, time_zone=>'America/Chicago');
	my $now = DateTime->today(time_zone=>'America/Chicago');
	die("Update publish date and version number in metadata.xml\n") if $now > $publishDate;
}
