#!/bin/sh
# for now, this'll only support "flat" cbz, i.e. no chapters
# also, it assumes "nice" names, make sure they're all "01.jpg", "02.png", etc...
exdir=$(mktemp -d)
mkdir "$exdir/in" "$exdir/out" "$exdir/out/META-INF"
unzip "$1" -d "$exdir/in"
echo '<?xml version="1.0"?><container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container"><rootfiles><rootfile full-path="package.opf" media-type="application/oebps-package+xml"/></rootfiles></container>' > "$exdir/out/META-INF/container.xml"
echo '<?xml version="1.0"?><package unique-identifier="pub-id" xmlns="http://www.idpf.org/2007/opf" version="3.0"><metadata xmlns:dc="http://purl.org/dc/elements/1.1/"><dc:identifier id="pub-id">urn:converted-cbz-sha256:'$(sha256sum "$1" | head -c 64)'</dc:identifier><dc:title>'"$(echo $1 | sed 's/</\&lt;/g; s/>/\&gt;/g')"'</dc:title><dc:language>en-EN</dc:language><meta property="dcterms:modified">'$(date -u +"%Y-%m-%dT%H:%M:%SZ")'</meta><meta property="rendition:layout">pre-paginated</meta></metadata><manifest><item id="nav" media-type="application/xhtml+xml" properties="nav" href="nav.xhtml"/>' > "$exdir/out/package.opf"
firstimage=' properties="cover-image"'
for image in "$exdir/in/"*
do
	ibase=$(basename "$image")
	echo '<item id="p'${ibase%%.*}'" media-type="application/xhtml+xml" href="'$ibase'.xhtml"/><item id="i'${ibase%%.*}'" media-type="'$(file -b --mime-type "$image")'" href="'$ibase'"'"$firstimage"'/>' >> "$exdir/out/package.opf"
	firstimage=''
done
echo '</manifest><spine>' >> "$exdir/out/package.opf"
#echo '</manifest><spine page-progression-direction="rtl">' >> "$exdir/out/package.opf"
for image in $(basename -a "$exdir/in/"*)
do
	echo '<itemref idref="p'${image%%.*}'"/>' >> "$exdir/out/package.opf"
done
echo '</spine></package>' >> "$exdir/out/package.opf"

for image in "$exdir/in/"*
do
	echo '<?xml version="1.0" encoding="UTF-8"?><html xmlns="http://www.w3.org/1999/xhtml"><head><title>Page '"$(basename "$image")"'</title><meta name="viewport" content="'$(identify -format 'width=%w, height=%h' "$image")'"/></head><body style="margin: 0"><img src="'"$(basename "$image")"'"/></body></html>' >> "$exdir/out/$(basename "$image").xhtml"
done
printf 'application/epub+zip' > "$exdir/out/mimetype"
echo '<?xml version="1.0" encoding="UTF-8"?><html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops"><head><title>Table of Contents</title></head><body><nav epub:type="toc"><ol><li><a href="'"$(basename $(ls $exdir/in/* | head -n1))"'.xhtml">First Page</a></li></ol></nav></body></html>' > "$exdir/out/nav.xhtml"
cd "$exdir/out"
mv ../in/* .
zip -Xr out.epub mimetype *
cd -
mv "$exdir/out/out.epub" "$1.epub"
rm -r "$exdir"
