#!/bin/bash

OS=`uname -a | cut -d " " -f 1 | sed "s/[^a-zA-Z0-9]//g"`
which ffmpeg >/dev/null || alias ffmpeg=avconv
ffmpeg -version >/dev/null 2>/dev/null || exit $?

humantime() {
	seconds=$1
	[ $timedelta ] && seconds=$((seconds + $timedelta))
	case $OS in
		"Darwin"|"FreeBSD")
		date -r $seconds +"%H:%M:%S"
		;;
		*)
		date -d @$seconds +"%H:%M:%S"
		;;
	esac
}

seconds() {
	string=$(echo $@ | sed "s| N/A||")
	case $OS in
		"Darwin"|"FreeBSD")
		seconds=$(date -j -f "%Y-%m-%d %H:%M:%S" "$string" +%s 2>/dev/null)
		# alias seconds=date -j -f "%Y-%m-%d %H:%M:%S" "1970-01-01 00:00:00" +"%Y-%m-%d %H:%M:%S %s"
		;;
		*)
		seconds=$(date -d "$string" +%s)
		;;
	esac
	if [ "$seconds" ]
	then
	    [ $timedelta ] && seconds=$((seconds - $timedelta))
	else
	    seconds=-1
	fi
	echo $seconds
	return
}
timedelta=$(seconds "1970-01-01 00:00:00")

total=0
for movie in "$@"
do
	[ -f "$movie" ] || continue
	printf "$movie: "
	# duration=$(ffmpeg -i "$movie" 2>&1 | grep Duration: | sed "s/.*Duration: //" | cut -d "," -f 1 | cut -d "." -f 1)
	# duration=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 -sexagesimal "$movie" | cut -d. -f 1)
#	seconds=0
	microseconds=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$movie")
	seconds=$(echo $microseconds | cut -d . -f 1)
	duration=$(humantime $seconds)
	printf "$duration $seconds"
	# seconds=$(seconds "1970-01-01 $duration")
	# printf " $(echo $seconds  | cut -d. -f 1) "
	total=$(echo "$microseconds + $total" | bc)
	echo
done

echo subtotal: $total
echo total: $total | cut -d. -f 1

# minutes=$(($total / 60))
echo "total $total"
minutes=$(echo "$total / 60" | bc -l)
echo minutes: $minutes
