#!/bin/bash

# avijoin by Kurt Neufeld
#
# based off of: http://www.doctort.org/adam/nerd-notes/concatenating-avi-files.html
#
# This script will join/concatenate several avi files together into one big
# one. And then (if available) it will run mencoder to fix the index. On my 
# machine (2GHz Core2 Duo with a slow SSD drive) it takes approx 1.5 minutes to 
# join two 720MB files into one 1.4GB file and fix the index.
#
# If you don't have mencoder the file should still be usable (with VLC) but 
# fast forwarding and reversing might be problematic.
#
# Released under MIT License - http://www.opensource.org/licenses/mit-license.html
#
# If you use/change this script a simple thank you would be very welcome.

if [[ -z "$@" || "$1" == "-h" || "$1" == "--help" ]]; then
	echo "usage: `basename $0` infile1 infile2 ... outfile"
	exit -1
fi

if [ $# -lt 3 ]; then
	echo "you need to supply at least 3 args: infile1 infile2 outfile"
	exit -1
fi

OUTFILE=${@: -1}
TEMPFILE="tmp_${RANDOM}.avi"

# INFILES[0]=$1 INFILES[1]=$2 etc, skip last element (the outfile)
for f in `seq $(($#-1))`; do
	INFILES[$(($f-1))]=${!f}
done

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

for fname in ${INFILES[*]}; do
	if [ ! -f "$fname" ]; then
		echo "File '$fname' does not exist. Aborting."
		exit -1
	fi
done

DRY=

echo -n "Merging... "
$DRY cat ${INFILES[*]} > $TEMPFILE
echo "done!"

#hash zmencoder 2>&- || { echo >&2 "I require mencoder but it's not installed.  Aborting."; exit 1; }
if `hash mencoder 2>&-` ; then
	$DRY mencoder -forceidx -oac copy -ovc copy $TEMPFILE -o "$OUTFILE"
fi

$DRY rm -f $TEMPFILE

IFS=$SAVEIFS

