#!/bin/bash

#Please change the below line to the path of your clit binary.
clit="clit"

#Please change the below line if your favorite html-viewer is not Firefox.
browser="firefox"



#If no arg, "-h" or "--help" print usage
if [ "$1" = "" ] || [ "$1" = "-h" ] || [ "$1" = "--help" ] ; then {
	echo 	"

Usage:
		
	cleanlit [lit-file]
		
Example:
		
	cleanlit /home/foo/ebooks/thisbook.lit
		
Please edit this script to enter the path of your clit binary and your 
html-viewer of choice.
		
You can obtain clit at http://www.convertlit.com/


"
	exit 0
} fi

#Making a randomly-named temporary directory
tmp=${TMPDIR-/tmp}
tmp=$tmp/cleanlit.$RANDOM.$RANDOM.$RANDOM.$$
(umask 077 && mkdir $tmp) || {
	echo "Could not create temporary directory! Exiting." 1>&2 
	exit 1
}

#Exploding the .lit file to that temporary directory
("$clit" "$1" "$tmp") || {
	echo "Clit failed. Exiting"
	exit 1
}
	
#getting number of htm files created by clit
htm=""; a=0
for i in /"$tmp"/*htm*; do
	htm[$a]="${i}"
	a=$(expr $a + 1)
done
	
	#if no files were created
	if [ ${#htm[*]} -eq 0 ]; then
		echo "<html>
		<head><title>Oops.</title></head>
		<body>Oops! Clit did not create any .lit files!
		</body>
		</html>" > "$tmp"/oops.html
		("$browser" "$tmp"/oops.html) || {
			echo "Your browser failed to open the file."
			exit 1
		}
	#if more than one file was created, make index page and display
	elif [ ${#htm[*]} -gt 1 ]; then
		if [ -a "$tmp"/Contents.htm* ] ; then
			("$browser" "$tmp"/Contents.htm*) || {
				echo "Your browser failed to open the file."
				exit 1
			}
		else
			echo "<html>
			<head><title>$1</title></head>
			<body><u><h3>Contents:</h3></u>
			<br />" > "$tmp"/clit.foo
			for i in /"$tmp"/*htm*; do
				link=${i##\/*\/}
				echo "<a href=\"/$i\">$link</a><br />" >>  "$tmp"/clit.foo
			done
			echo "</body></html>" >> "$tmp"/clit.foo
			mv "$tmp"/clit.foo "$tmp"/clit.html
			("$browser" "$tmp"/clit.html) || {
				echo "Your browser failed to open the file."
				exit 1
			}
		fi
	else #if only one htm file was created, display it
		#Opening the .htm file with the browser
		("$browser" "$tmp"/*htm) || {
			echo "Your browser failed to open the file."
			exit 1
		}
	fi