#!/bin/bash

set -e
export LANG=en_US

movie_name="$1"
movie_fps="$2"
frame_format=jpeg
frame_suffix=.jpg
#frame_format=png
#frame_suffix=.png
movie_recoded="${movie_name}.avi.tmp"
movie_subtitles="${movie_name}.txt"

if [ -z "$movie_name" ]; then
	echo "avi2cbz v0.1 (license: WTFPL, http://en.wikipedia.org/wiki/WTFPL)"
	echo
	echo "Usage: avi2cbz.sh \"Movie Name\""
	echo "                            (^ without file extension)"
	echo
	echo "Input Files: Movie Name.avi (source video)"
	echo "             Movie Name.txt (subtitles in MicroDVD format)"
	echo
	echo "Output Files: Movie Name-avi2cbz-images (video images with subtitles)"
	echo "              Movie Name.cbz (video images in Comic Archive format)"
	echo "              Movie Name.avi.tmp (a temporary video with all keyframes)"
	echo
	echo "Required Tools: mencoder, mplayer, zip, fdupes (optional)"
	echo
	exit 1
fi

out_dir="${movie_name}-avi2cbz-images"
rm -fr "$out_dir"
mkdir -p "$out_dir"

# Detect movie FPS

if [ -z "$movie_fps" ]; then
	video_fps_id=`mplayer -frames 0 -identify "${movie_name}.avi" 2>&1 | grep "ID_VIDEO_FPS=" || true`
	if [ "$video_fps_id" == "" ]; then
		echo "ERROR: mplayer returned no ID_VIDEO_FPS info!"
		echo "       Please specify movie FPS."
		echo "       Example: avi2cbz.sh \"Movie Name\" 23.976"
		exit 1
	fi
	
	movie_fps="${video_fps_id:13}"
fi
echo "==== Using $movie_fps movie FPS"

image_num=0
total_images=$(cat "${movie_subtitles}"|wc -l)

function dump()
{
	DEBUG=-really-quiet
	mplayer $DEBUG \
		-ss "$1" -frames 1 \
		-nosound -vo "$frame_format:outdir=${out_dir}:quality=85:smooth=0" "${movie_recoded}" \
		-vf pp \
		2&>/dev/null

#	if [ "$frame_format" == "png" ]; then
#		optipng "${out_dir}/00000001.png"
#	fi
	mv "${out_dir}/00000001${frame_suffix}" "$out_dir/${image_num}${frame_suffix}"
}

function cleanup()
{
	rm -f "${out_dir}/00000001.jpg"
	rm -f "${out_dir}/00000001.png"
}
trap cleanup SIGINT

function cleanup_mencoder()
{
	rm -f "$movie_recoded"
}

# HACK: Recode input video because the -ss option sucks

echo "===="
echo "==== RECODING AND BURNING SUBTITLES: ${movie_name}.avi + ${movie_subtitles} -> ${movie_recoded}"
echo "===="
if ! [ -f "${movie_recoded}" ]; then
	trap cleanup_mencoder SIGINT
	mencoder \
		-font "Bitstream Vera Sans" -sub "${movie_subtitles}" -subcp "cp1250" \
		-subfont-text-scale 3 -subpos 90 \
		-nosound -ovc lavc -lavcopts vcodec=mpeg4:keyint=0 -o "${movie_recoded}" \
		"${movie_name}.avi"
	trap - SIGINT
else
	echo "==== ${movie_recoded} already exists, skipping..."
	echo "===="
fi

# Dump video images

exec 3< "${movie_subtitles}"
while read <&3; do
	let image_num=image_num+1;
	i=$(expr index "$REPLY" "}")
	frame=${REPLY:1:i-2}

	# http://lists.netisland.net/archives/plug/plug-2009-09/msg00225.html
function newceil() {
	echo "define ceil (x) {if (x<0) {return x/1} \
    else {if (scale(x)==0) {return x} else {return x/1 + 1 }}} ; \
        scale=0; y=$1; scale=2; ceil(y)" | bc; }
        #pos=$(newceil "$frame / $movie_fps + 1")

	if [ "$movie_fps" == "23.976" ]; then
		pos=`echo "scale=2; $frame / $movie_fps + 1"|bc`
	else
		
		pos=`echo "scale=0; $frame / $movie_fps + 1"|bc`
	fi
	echo -e -n "\r==== PIRATING: frame=$frame, pos=$pos ($image_num/$total_images)"
	#echo "$frame/$pos: $REPLY"
	dump "$pos"
#	break
done

echo

# Make nice names (1.jpg -> image-00000001.jpg)

for ((i=1;i<=$image_num;i++)); do
	from="${out_dir}/${i}${frame_suffix}"
	to="${out_dir}/image-$(printf "%08d\n" "$i")${frame_suffix}"
	echo "${from} -> ${to}"
	mv "${from}" "${to}" || true
done

# Remove duplicated images

fdupes --delete --noprompt "$out_dir" || true

# Create Comic Archive (CBZ)

rm -f "$movie_name.cbz"
pushd "$out_dir"
zip "../$movie_name.cbz" *.jpg
popd

echo -e "\aDONE!\n"
