### ffmpeg-x265-main10
# Transcode the videos in a given directory with x265's main10 profile, then put them in a
# subdirectory for easy replacement after manually checking results.

RESULTS_DIRECTORY_NAME="_x265_main10"

# TODO: This variable isn't referenced because I didn't figure out how to put it in the glob it
# needs to be in. Fix that.
VIDEO_EXTENSIONS="mkv,mp4,avi"

_ffmpeg_x265_main10_ffmpeg () {
	original_file="$1"
	results_directory="$2"
	partial_file="${results_directory}/$(basename "${original_file}").part"
	complete_file="${results_directory}/$(basename "${original_file}")"
	mkdir -p "$results_directory"

	if [ -e "$complete_file" ]; then
		echo "${complete_file} already exists, skipping."

	else
		ffmpeg -n -i "$original_file" \
			-map 0:v:0 -c:v libx265 -preset medium -profile:v main10 \
			-map 0:a -c:a copy \
			-map '0:s?' -c:s copy \
			-f matroska \
			"$partial_file" \
			|| rm "$partial_file"

		if [ -e "$partial_file" ]; then
			mv "$partial_file" "$complete_file"
		fi
	fi

	if [ -e "$destination" ]; then
		rmdir --ignore-fail-on-non-empty "$destination"
	fi
}

arg_file="$1"

if [ -z "$arg_file" ]; then
	arg_file=.
fi

if [ -f "$arg_file" ]; then
	destination="${arg_file:h}/${RESULTS_DIRECTORY_NAME}"
	_ffmpeg_x265_main10_ffmpeg "$arg_file" "$destination"

elif [ -d "$arg_file" ]; then
	destination="${arg_file}/${RESULTS_DIRECTORY_NAME}"

	# List all the video files in an array for future expansions like:
	#	- A prompt before you commit to hours of transcoding.
	#	- Removing items that are already completed.
	#	- Interactively discarding list items
	#	- etc.
	# TODO: Use $VIDEO_EXTENSIONS here instead of hard-coding extension names.
	files=($arg_file/*.{mkv,mp4,avi}(N))
	for fname in $files; do
		_ffmpeg_x265_main10_ffmpeg "$fname" "$destination"
	done

else
	echo "ffmpeg_x265_main10: Error:${arg_file} is not a file or directory."
fi

# vim:syntax=sh filetype=sh
