#!/bin/bash
# eti-video - small converter by Katja (fly5.kapsi.fi)
##
# convert those eti camcorder .ear and .eye files to avi
# if ear or eye missing will convert the one we found to
# either mp3 or mpg..
##
# in zsh whole folder could be converted with this:
# for i in *.eye; do eti-video ./${i:r}; done
# ./ start because of the files that start with -
##

# this is (hopefully) the only option you should care about.
# do you want to remove .mp3 and .mpg files after they are
# joined as a single .avi?
remove=true

# ok this can be interesting too.. want to open file right after
# converting? put app from your path e.g. "mplayer" or leave empty.
openfile=""

function usage() {
cat <<EOF
Usage: `basename $0` filename-without-extension
e.g. convert testi.ear and testi.eye to testi.avi
 $ `basename $0` testi
EOF
exit 0
}

# noargs > usage
[ -z "$1" ] && usage

convert="$1"
ear="$convert.ear"
eye="$convert.eye"
avi="$convert.avi"

# if no .ear
if [ ! -f "$ear" ]; then
#	echo "Not found: $ear"
	ear2=""
else
	ear2="ear"
fi

# if no .eye
if [ ! -f "$eye" ]; then
#	echo "Not found: $eye"
	eye2=""
else
	eye2="eye"
fi

# everything ok?
function errorcheck() {
	if [ "$?" -eq 0 ]; then
		#echo -ne "..OK.\n"
		echo ""
	else
		echo '..error. Aborting'
		exit 1
	fi
}

# converting functions
function audio() {
	echo "Converting $1.ear to $1.mp3"
	ffmpeg -i $1.ear -acodec mp3 $1.mp3
errorcheck
}

function video() {
	echo "Converting $1.eye to $1.mpg"
	mencoder -ovc lavc -o $1.mpg $1.eye
errorcheck
}

function join() {
	echo "Joining $1.mpg and $1.mp3 to $1.avi"
	ffmpeg -i $1.mpg -i $1.mp3 -ab 56 -ar 22050 -b 500 -s 640x480 $1.avi
errorcheck
}

# let's do something
case x$ear2$eye2 in
	x)	echo "No such files \"$ear\" or \"$eye\". Aborting."
		exit 1
;;
	xear)
		echo "Found $ear, converting to mp3"
		audio "$convert"
		file="$convert.mp3"
;;
	xeye)
		echo "Found $eye, converting to mpg"
		video "$convert"
		file="$convert.mpg"
;;
	xeareye)
		echo "Found $ear and $eye, converting them to $avi"
		audio "$convert"
		video "$convert"
		join "$convert"
			if [ "$remove" = "true" ]; then
				# move that -f to -i if you want to be asked before
				echo "Cleaning: $convert.mp3 $convert.mpg"
				rm -f $convert.mp3 $convert.mpg
			fi
		file="$convert.avi"
;;
	*) 	echo "Something is really wrong. Aborting."
	   	exit 1
;;
esac

echo "File: $file"

if [ -n "$openfile" ]; then
	$openfile "$file"
fi

exit $?
