#!/bin/sh

mkdir -p coverart

echo "<html>"
echo "<head>"
echo "<title>Videos</title>"
echo "</head>"
echo "<body bgcolor=\"black\" text=\"white\" link=\"white\" vlink=\"white\">"
echo "<center>"
echo "<table cellspacing=\"20\">"

numcols=4
curcols=0
maxartheight=240
maxartwidth=200
for a in *.m4v; do
	if [ "$a" == "*.m4v" ]; then
		break;
	fi
	remainder=`expr $curcols % $numcols`
	if [ "$remainder" -eq 0 ]; then
		echo "<tr>"
	fi
	echo "<td align=\"center\">"
	nosuffix=`echo $a | sed -e 's/\..*$//'`;
	mp4art --art-any --extract "$a" > /dev/null 2>&1
	arttype=""
	for at in png jpg; do
		coverart="${nosuffix}.art[0].${at}"
		if [ -f "$coverart" ]; then
			arttype=$at
			break;
		fi
	done
	if [ "$arttype" == "" ]; then
		arttype="jpg"
		coverart="coverart/${nosuffix}.${arttype}"
		ffmpeg -i "$a" -vframes 1 -ss 30 "$coverart" > /dev/null 2>&1
		sips --resampleWidth $maxartwidth "$coverart" > /dev/null 2>&1
	elif [ -f "$coverart" ]; then
		mv "$coverart" "coverart/${nosuffix}.${arttype}";
		rm -f "${nosuffix}.art*"
		sips --resampleHeight $maxartheight "coverart/${nosuffix}.${arttype}" > /dev/null 2>&1
	fi
	sips --cropToHeightWidth $maxartheight $maxartwidth "coverart/${nosuffix}.${arttype}" > /dev/null 2>&1

	contentname=`mp4info "$a" | grep Name | sed -e 's/\ Name:\ //'`
	if [ -z "$contentname" ]; then
		contentname="$nosuffix"
	fi
	echo "<a href=\"$a\"><img src=\"coverart/${nosuffix}.${arttype}\"/></a><br>"
	echo $contentname
	echo "</td>"

	curcols=`expr $curcols + 1`
	remainder=`expr $curcols % $numcols`
	if [ "$remainder" -eq 0 ]; then
		echo "</tr>"
	fi
done

for a in *; do
	if [ ! -d "$a" ]; then
		continue;
	fi

	if [ "$a" == "coverart" ]; then
		continue;
	fi

	if [ ! -f "${a}/.dirart.jpg" ]; then
		firstcoverart=`find "$a" -type f | grep coverart | head -1`;
		if [ -f "$firstcoverart" ]; then
			sips --resampleHeight 240 --setProperty format jpeg "$firstcoverart" --out "$a/.dirart.jpg" > /dev/null 2>&1
		fi
	fi

	remainder=`expr $curcols % $numcols`
	if [ "$remainder" -eq 0 ]; then
		echo "<tr>"
	fi

	echo "<td align=\"center\">"
	dirlink="$a"
	if [ -f "${a}/index.html" ]; then
		dirlink="${a}/index.html"
	fi
	if [ -f "${a}/.dirart.jpg" ]; then
		echo "<a href=\"$dirlink\"><img src=\"${a}/.dirart.jpg\"/></a><br>"
		echo "$a<br>"
		echo "(Directory)"
	else
		echo "<a href=\"$dirlink\">$a</a>"
	fi
	echo "</td>"

	curcols=`expr $curcols + 1`
	remainder=`expr $curcols % $numcols`
	if [ "$remainder" -eq 0 ]; then
		echo "</tr>"
	fi
done

echo "</table>"
echo "</center>"
echo "</body>"
echo "</html>"
