# Copyright 2026 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

DESCRIPTION="Manage torchaudio backend (ROCm/CUDA)"
VERSION="0.1"

TORCHAUDIODIR="${EROOT}/usr/lib/torchaudio"

find_site_dirs() {
	local dirs=()
	local d
	for d in "${EROOT}"/usr/lib/python3.*/site-packages; do
		[[ -d "${d}" ]] && dirs+=("${d}")
	done
	echo "${dirs[@]}"
}

find_targets() {
	local targets=()
	local d
	for d in "${TORCHAUDIODIR}"/*/; do
		[[ -d "${d}torchaudio" ]] && targets+=("$(basename "${d}")")
	done
	echo "${targets[@]}"
}

get_active() {
	local sitedirs=( $(find_site_dirs) )
	[[ ${#sitedirs[@]} -eq 0 ]] && return
	if [[ -L "${sitedirs[0]}/torchaudio" ]]; then
		local target
		target=$(readlink "${sitedirs[0]}/torchaudio")
		target=${target#../../torchaudio/}
		target=${target%%/*}
		echo "${target}"
	fi
}

remove_symlinks() {
	local d
	for d in $(find_site_dirs); do
		rm -f "${d}/torchaudio"
	done
}

set_symlinks() {
	local target="${1}"
	local prefix="${TORCHAUDIODIR}/${target}"

	if [[ ! -d "${prefix}/torchaudio" ]]; then
		die -q "Target '${target}' not found: ${prefix}/torchaudio"
	fi

	local d
	for d in $(find_site_dirs); do
		ln -s "../../torchaudio/${target}/torchaudio" "${d}/torchaudio"
	done
}

### list action ###

describe_list() {
	echo "List available torchaudio backends"
}

do_list() {
	local targets=( $(find_targets) )
	local active=$(get_active)
	local i

	write_list_start "Available torchaudio backends:"
	for (( i = 0; i < ${#targets[@]}; i++ )); do
		if [[ "${targets[i]}" == "${active}" ]]; then
			targets[i]=$(highlight_marker "${targets[i]}")
		fi
	done
	write_numbered_list -m "(none available)" "${targets[@]}"
}

### show action ###

describe_show() {
	echo "Show the current torchaudio backend"
}

do_show() {
	local active=$(get_active)
	echo "${active:-(unset)}"
}

### set action ###

describe_set() {
	echo "Set the torchaudio backend"
}

describe_set_parameters() {
	echo "<target>"
}

describe_set_options() {
	echo "target : Target name or number (from 'list' action)"
}

do_set() {
	local target="${1}"

	if [[ -z "${target}" ]]; then
		die -q "Required parameter 'target' missing"
	fi

	local targets=( $(find_targets) )
	if is_number "${target}"; then
		target=${targets[$((target - 1))]}
	fi

	local found=0
	local t
	for t in "${targets[@]}"; do
		[[ "${t}" == "${target}" ]] && found=1
	done
	if [[ ${found} -eq 0 ]]; then
		die -q "Invalid target '${target}'"
	fi

	remove_symlinks
	set_symlinks "${target}"
}
