#!/usr/bin/env bash

# Copyright © 2012-2026 ScriptFanix
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# A copy of the GNU General Public License v3 is includded in the LICENSE file
# at the root of the project.

encodeFile::opus() {
	# Build opusenc VBR encode command
	opusencopts=(${ionice}opusenc --quiet)
	opusencopts+=(--bitrate ${destinationquality[$destination]})
	# Add Forward Error Correction if a packet loss percentage was
	# configured
	[ -n "${destinationloss["$destination"]}" ]	\
	&& opusencopts+=(--expect-loss "${destinationloss["$destination"]}")
	# Embed Ogg comment tags
	[ -n "$albumartist" ] && opusencopts+=(--comment "ALBUMARTIST=$albumartist")
	[ -n "$album"	] && opusencopts+=(--comment "ALBUM=$album")
	[ -n "$artist"	] && opusencopts+=(--artist "$artist")
	[ -n "$composer" ] && opusencopts+=(--comment "COMPOSER=$composer")
	[ -n "$disc"	] && opusencopts+=(--comment "DISCNUMBER=$disc")
	[ -n "$genre"	] && opusencopts+=(--comment "GENRE=$genre")
	[ -n "$performer" ] && opusencopts+=(--comment "PERFORMER=$performer")
	[ -n "$rating" ] && opusencopts+=(--comment "FMPS_RATING=$rating")
	[ -n "$releasecountry" ] \
		&& opusencopts+=(--comment "RELEASECOUNTRY=$releasecountry")
	[ -n "$replaygain_alb" ] 					\
		&& opusencopts+=(--comment)				\
		&& opusencopts+=("REPLAYGAIN_ALBUM_GAIN=$replaygain_alb")
	[ -n "$replaygain_trk" ] 					\
		&& opusencopts+=(--comment)				\
		&& opusencopts+=("REPLAYGAIN_TRACK_GAIN=$replaygain_trk")
	[ -n "$title"	] && opusencopts+=(--title "$title")
	# Split "track/total" format: opusenc uses separate TRACKNUMBER and
	# TRACKTOTAL fields
	[ -n "$track"	] && opusencopts+=(--comment "TRACKNUMBER=${track%/*}")
	[ -n "${track#*/}" ] && opusencopts+=(--comment "TRACKTOTAL=${track#*/}")
	[ -n "$year"	] && opusencopts+=(--comment "DATE=$year")
	opusencopts+=("$tempdir/$tmpfile".wav "${destinationpath[$destination]}/$destdir/$destfile.opus")
	encodetaskid=$(
		Insert tasks <<-EOInsert
			key		${fileid}opusenc$destination
			requires	${soxtaskid:-$decodetaskid}
			fileid		$destfileid
			filename	$destdir/$destfile.opus
			$(
				# Escape special characters that could
				# interfere with bash glob/brace expansion
				for key in ${!opusencopts[@]}
				do
					cleanedopts="${opusencopts[key]//\&/\\\&}"
					cleanedopts="${cleanedopts//\[/\\[}"
					cleanedopts="${cleanedopts//\]/\\]}"
					cleanedopts="${cleanedopts//\{/\\{}"
					cleanedopts="${cleanedopts//\}/\\\}}"
					echo "cmd_arg$key $cleanedopts"
				done
			)
			source_file	$fileid
			status		0
			rename_pattern	${destinationrenamepath[$destination]}/${destinationrename[$destination]}
			fat32compat	${destinationfat32compat["$destination"]}
			ascii		${destinationascii["$destination"]}
		EOInsert
	)
	# Increment parent task's required_by counter so it won't clean up
	# until all children finish
	parent_required=$(
		Select tasks required_by			\
			<<<"id = ${soxtaskid:-$decodetaskid}"
	)
	Update tasks required_by $((++parent_required))	\
		<<<"id = ${soxtaskid:-$decodetaskid}"
	progressSpin
	soxtaskid=''
}
