#!/bin/sh
#
# Convert input file to x265 :
# * Keep only the first audio track (-map 0:a:0)
# * Keep all subtitles (-map 0:s)
# * Use fast preset for encoding
# * Simply add "x265" at the end of the file (before the extension)
# * Only print progression

# Colors {{{
readonly RED='\033[0;31m'
readonly RESET='\033[0m'
# }}}

x265_convert() {
	orig_file="${1}"
	file_name=$(echo "${orig_file}" | sed -e 's/\.[^.]*$//')  # without extension
	#file_name="${1%.*}" # bash only
	file_ext=$(echo "${orig_file}" | sed -e 's/.*\.//')  # without extension
	dest_file="${file_name}.x265.${file_ext}"

	## If subtitles are available
	if [ $(ffprobe -loglevel error -select_streams s -show_entries stream=index:stream_tags=language -of csv=p=0 "${orig_file}" | wc --lines) -eq "0" ]; then
		printf "%b\n" "Try to convert original file (${orig_file}) with ffmpeg… without subtitles."
		ffmpeg -loglevel quiet -stats -i "${orig_file}" -codec:v libx265 -preset fast -crf 28 -codec:a copy -map 0:v -map 0:a:0 "${dest_file}"
	else
		printf "%b\n" "Try to convert original file (${orig_file}) with ffmpeg… with subtitles."
		ffmpeg -loglevel quiet -stats -i "${orig_file}" -codec:v libx265 -preset fast -crf 28 -codec:a copy -codec:s copy -map 0:v -map 0:a:0 -map 0:s "${dest_file}"
	fi

	printf "%b\n" "New x265 file is available ( ${RED}${dest_file}${RESET} )."
}

x265_convert "${1}"