#! /bin/sh

#Set temporary directory
tmpdir=/tmp/vidpack

#Without temporary directory
if [ ! -d "$tmpdir" ]; then
	#Create temporary directory or die
	mkdir -p "$tmpdir" || exit 1;
fi

#Set time as utc
export TZ="utc"

#Iterate on each video in cur dir older than 1h
#for i in `find $docdir -maxdepth 1 -type f,l -name '*.mov' -o -name '*.mp4' -mmin +60`; do
#for i in `find . -maxdepth 1 -type f \( -name '*.mp4' -o -name '*.avi' -o -name '*.mpg' -o -name '*.mkv' \)`; do
find . -maxdepth 1 -type f \( -iname '*.mov' -o -iname '*.mp4' -o -iname '*.avi' -o -iname '*.mpg' -o -iname '*.mkv' \) -print0 | while read -d $'\0' i; do
	#Set file date
	fdate=$(date -u --rfc-3339=ns -r "$i" | perl -pne 's/\..*$/.000000Z/; s/ /T/');

	#Without file content
	if [ -s "$i" ]; then
		#File must not be empty
		continue;
	fi

	#Without file date
	if [ -z "$fdate" ]; then
		#File date must exists
		exit 1;
	fi

	#Set name date
	#XXX: may miss if filename don't match /^(.*[^0-9])?YYYYMMDD[^0-9]?HHMMSS([^0-9].*)?$/
	ndate=$(echo "$i" | perl -ne 'print if s/^(?:.*[^0-9])?([0-9]{4})([0-9]{2})([0-9]{2})(?:[^0-9])?([0-9]{2})([0-9]{2})([0-9]{2})(?:[^0-9].*)?$/\1-\2-\3T\4:\5:\6.000000Z/');

	#Without name date
	if [ -z "$ndate" ]; then
		#Set name date
		#XXX: catch when filename match only /^(.*[^0-9])?20YYMMDD([^0-9].*)?$/
		ndate=$(echo "$i" | perl -ne 'print if s/^(?:.*[^0-9])?(20[0-9]{2})([0-9]{2})([0-9]{2})(?:[^0-9].*)?$/\1-\2-\3T00:00:00.000000Z/');
	fi

	#Set create date
	cdate=$(ffprobe -hide_banner -v error -show_entries format_tags=date,creation_time,com.apple.quicktime.creationdate -of default=nokey=1:noprint_wrappers=1 -i "$i" 2> /dev/null | perl -ne '$l = $_ unless /^$/; END { chomp $l; print $l }');

	#Set best date
	date=$(echo -e "$fdate\n$ndate\n$cdate" | perl -ne '$l = $_ unless /^(0000:00:00 00:00:00|)$/; END { chomp $l; print $l }');

	#Set dest filename
	dest="$(echo "$i" | perl -pne 's/\.(?:mp4|avi|mpg|mkv)$//').webm";

	#Set passlog filename
	passlog="$tmpdir/$(echo "$i" | perl -pne 's%(?:.*/)([^/]+)\.(?:mp4|avi|mpg|mkv)$%\1%;s% %_%g')";

	#With passlog file
	#if [ -f "$passlog-0.log" ]; then
	#	#Display error
	#	echo "Operation in progress: $passlog-0.log exists"
	#
	#	#Exit with failure
	#	exit 1;
	#fi

	#Set source rate
	sourcerate=$(ffprobe -hide_banner -v quiet -select_streams v:0 -show_entries stream=bit_rate -of default=nokey=1:noprint_wrappers=1 "$i" | perl -ne 'chomp; print');

	#Set bitrate
	bitrate=256k

	#With sourcerate >= 5120k (1080p)
	if [ $sourcerate -ge 5120000 ]; then
		#Set bitrate
		bitrate=5120k
	#With sourcerate >= 2560k (720p)
	elif [ $sourcerate -ge 2560000 ]; then
		#Set bitrate
		bitrate=2560k
	#With sourcerate >= 1024k
	elif [ $sourcerate -ge 1024000 ]; then
		#Set bitrate
		bitrate=1024k
	#With sourcerate >= 512k
	elif [ $sourcerate -ge 512000 ]; then
		#Set bitrate
		bitrate=512k
	fi

	#With dest existing
	if [ ! -f "$dest" ]; then
		#Without passlog file
		if [ ! -f "$passlog-0.log" ]; then
			#First pass
			#ffmpeg -i "$i" -v error -passlogfile "$passlog" -c:v libaom-av1 -b:v "$bitrate" -pass 1 -an -f null /dev/null < /dev/null;
			ffmpeg -i "$i" -v error -passlogfile "$passlog" -c:v libvpx-vp9 -b:v "$bitrate" -pass 1 -an -f null /dev/null < /dev/null;

			#With first pass
			if [ $? != 0 ]; then
				#Skip to next run
				continue;
			fi
		fi

		#With passlog file
		if [ -f "$passlog-0.log" ]; then
			#Second pass
			#XXX: see http://wiki.webmproject.org/webm-metadata/global-metadata#TOC-Official-Tags
			#ffmpeg -y -i "$i" -v error -passlogfile "$passlog" -c:v libaom-av1 -b:v "$bitrate" -pass 2 -pix_fmt yuv420p -c:a libopus -movflags +faststart -metadata creation_time="$date" -fflags +bitexact "$dest" < /dev/null;
			ffmpeg -y -i "$i" -v error -passlogfile "$passlog" -c:v libvpx-vp9 -b:v "$bitrate" -pass 2 -pix_fmt yuv420p -c:a libopus -movflags +faststart -metadata creation_time="$date" -fflags +bitexact "$dest" < /dev/null;

			#With second pass pass
			if [ $? = 0 ]; then
				#With non empty dest file
				#if [ -s "$dest" ]; then
				#	#Remove source file
				#	unlink "$i";
				#fi

				#With passlog file
				if [ -f "$passlog-0.log" ]; then
					#Remove passlog file
					unlink "$passlog-0.log";
				fi
			fi
		fi
	fi
done

#Remove temporary directory
rmdir "$tmpdir" || true;

#Exit with success
exit 0;