#!/usr/bin/env bash
#
# Description: Converts audio to 256Kb/s *.opus
#
# Homepage: https://codeberg.org/krathalan/miscellaneous-scripts
#
# Copyright (C) 2019-2024 Hunter Peavey
#
# 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, or
# (at your option) any later version.
#
# 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

# -----------------------------------------
# -------------- Guidelines ---------------
# -----------------------------------------

# This script follows the Google Shell Style Guide:
# https://google.github.io/styleguide/shell.xml

# This script uses shellcheck: https://www.shellcheck.net/

# See https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
set -Eeuo pipefail

# This script spawns subshell processes
trap 'killall background' SIGINT

# -----------------------------------------
# ----------- Program variables -----------
# -----------------------------------------

# Colors
RED=$(tput bold && tput setaf 1)
NC=$(tput sgr0) # No color/turn off all tput attributes
readonly RED NC

# -----------------------------------------
# --------------- Functions ---------------
# -----------------------------------------

#######################################
# Converts a file to an opus file.
# Globals:
#   none
# Arguments:
#   $1: base file name to convert
#   $2: origin file format
# Returns:
#   none
#######################################
convert_file()
{
	# Overwrite if present
	rm -f "$1.opus"

	ffmpeg -loglevel panic -i "$1.$2" -c:a libopus -b:a 256K "$1.opus"
}

#######################################
# Prints passed error message before premature exit.
# Prints everything to >&2 (STDERR).
# Globals:
#   RED, NC
#   SCRIPT_NAME
# Arguments:
#   $1: error message to print
# Returns:
#   none
#######################################
exit_script_on_failure()
{
  printf "%sError%s: %s\n" "${RED}" "${NC}" "$1" >&2
  exit 1
}

# -----------------------------------------
# ---------------- Script -----------------
# -----------------------------------------

[[ "$(whoami)" = "root" ]] &&
  exit_script_on_failure "This script should NOT be run as root (or sudo)!"

[[ $# -lt 1 ]] &&
  exit_script_on_failure "Please specify an origin format (e.g. flac)."

readonly ORIGINFORMAT="$1"

fileName=""

for file in "$PWD"/*."${ORIGINFORMAT}"; do
	fileName="$(basename -- "${file}")"
	fileName="${fileName%.*}"

	convert_file "${fileName}" "${ORIGINFORMAT}" &
done

# Track progress
filesToProcess=$(find . -name "*.${ORIGINFORMAT}" | wc -l)
# shellcheck disable=SC2207
joblist=($(jobs -p))
joblistLength=${#joblist[*]}
percentageComplete="0"

while (( joblistLength > 1 )); do
  sleep 2

  # Refresh data
	# shellcheck disable=SC2207
  joblist=($(jobs -p))
  joblistLength=${#joblist[*]}
  percentageComplete="$(awk '{printf "%.0f", $1/$2*100}' <<< "$(( filesToProcess - joblistLength )) ${filesToProcess}")"

	printf "\r%s/%s files processed. %s%% complete" $(( filesToProcess - joblistLength )) "${filesToProcess}" "${percentageComplete}"
done

wait

if [[ ! -d "${ORIGINFORMAT}" ]]; then
	mkdir "${ORIGINFORMAT}"/
fi

mv ./*."${ORIGINFORMAT}" "${ORIGINFORMAT}"/

printf "\n\nDone.\n"
