#!/bin/bash
#-----------------------------------------------------------------------------------------------------------------------------------
#
# Album Convert
# 
# Copyright (C) 2016-2026 Arnaud G. GIBERT
# mailto:arnaud@rx3.net
# 
# This is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser 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/>.
# 
#-----------------------------------------------------------------------------------------------------------------------------------



#-----------------------------------------------------------------------------------------------------------------------------------
# Includes
#-----------------------------------------------------------------------------------------------------------------------------------

: "${RX3_LIB_DIR:=/usr/lib/rx3}"
. "${RX3_LIB_DIR}/music_tools.bash"





#-----------------------------------------------------------------------------------------------------------------------------------
# Global Variables
#-----------------------------------------------------------------------------------------------------------------------------------

declare -g    VERSION="1.1.0"
declare -g       NAME="album_convert"
declare -g       HELP="usage: [-h | --help] | [-V | --version] | [-T | --test] [-v | --verbose] [-r | --resample] [-d | --downsampled_tag] <source_dir> <target_dir>"

declare -g   RESAMPLE="FALSE"
declare -g      DSTAG="FLASE"
declare -g SOURCE_DIR=""
declare -g TARGET_DIR=""
       
declare -g       MODE="DEFAULT"
declare -g    VERBOSE="FALSE"
declare -g    DRY_RUN="FALSE"





#-----------------------------------------------------------------------------------------------------------------------------------
# Version Print
#-----------------------------------------------------------------------------------------------------------------------------------

ac_version_print()
{
    version_print
}





#-----------------------------------------------------------------------------------------------------------------------------------
# Help Print
#-----------------------------------------------------------------------------------------------------------------------------------

ac_help_print()
{
    ac_version_print
    help_print
}





#-----------------------------------------------------------------------------------------------------------------------------------
# Arg Parse
#-----------------------------------------------------------------------------------------------------------------------------------

ac_args_parse()
{
    tmp_args=$(getopt -o ThVvrd --long test,help,version,verbose,resample,downsampled_tag -n "${NAME}" -- "$@")

    if [ $? != 0 ] ; then echo_error "Terminating..." ; exit 1 ; fi

    # Note the quotes around `$TEMP': they are essential!
    eval set -- "${tmp_args}"

    while true
    do
	case "$1" in
	    # Options

	    # Mode switches
            -T|--test)                                         MODE="TEST";                   shift;;
	    -h|--help)                                         MODE="EXIT"; ac_help_print;    shift;;
	    -V|--version)                                      MODE="EXIT"; ac_version_print; shift;;

	    # Global options
            -v|--verbose)                                   VERBOSE="TRUE";                   shift;;
            -r|--resample)                                 RESAMPLE="TRUE";                   shift;;
            -d|--downsampled_tag)                             DSTAG="TRUE";                   shift;;

            # End of options
	    --)                                                                               shift;  break;;
	    *) echo "args_parse internal error [$1] !";                                               exit 1;;
	esac
    done

    if [[ "${MODE}" != "EXIT" ]]
    then
        if [[ "${#}" != "2" ]]
	then
	    if [[ "${#}" -lt "2" ]]
	    then
		echo_error "Not enough args!"
	    else
		echo_error "Too many args!"
	    fi

	         MODE="EXIT"
	    ac_help_print
	else
	   SOURCE_DIR="$1"
	   TARGET_DIR="$2"
	fi
    fi
}





#-----------------------------------------------------------------------------------------------------------------------------------
# Main
#-----------------------------------------------------------------------------------------------------------------------------------

ac_args_parse "$@"



if [[ "${MODE}" == "EXIT" ]]
then
    exit 0
else
    if [[ "${MODE}" == "TEST" ]]
    then
	DRY_RUN="TRUE"
    fi
fi

if [[ "${RESAMPLE}" == "TRUE" ]]
then
    resample_flags="-af aresample=out_sample_fmt=s16:out_sample_rate=44100"
else
    resample_flags=""
fi



echo_error "${NAME}: Mode: [${MODE}]   Verbose: [${VERBOSE}]   Resample : [${RESAMPLE}]   DownSampled_Tag : [${DSTAG}]   Source_Dir: [${SOURCE_DIR}]   Target_Dir: [${TARGET_DIR}]"

if [[ ! -d "${TARGET_DIR}" ]]
then
    echo_error "Target directory doesn't exit !"
    exit -1
fi

for file in "${SOURCE_DIR}"/*@(.flac|.ogg|.mp3|.m4a|.ape|.wav)
do
             id="$(basename "${file}" | sed -e "s/-.*//")"
    target_file="${TARGET_DIR}/$(basename "${file}" | sed -e 's/\.[^.]*$//').flac"

    cmd_exec ffmpeg -i "${file}" -compression_level 12 ${resample_flags} "${target_file}"
done
set -x
if [[ "${RESAMPLE}" == "TRUE" ]]
then
    for file in "${TARGET_DIR}"/*.flac
    do
	if [[ "${DSTAG}" == "TRUE" ]]
        then
	    tag="DESCRIPTION"

	    value="$(mt_tag_read "${file}" "${tag}")"

	    if [[ "$( echo "${value}" | grep "Downsampled")" == "" ]]
	    then
		value="${value}\nDownsampled"
		mt_tag_delete "${file}" "${tag}"
		mt_tag_write  "${file}" "${tag}" "${value}"
	    fi
	fi

	for tag in "ALBUM" "TITLE"
	do
	        value="$(mt_tag_read "${file}" "${tag}")"
	    new_value="$(echo ${value} | sed -e 's/ - HD$//')"

	    if [[ "${value}"  != "${new_value}" ]]
	    then
		mt_tag_delete "${file}" "${tag}"
		mt_tag_write  "${file}" "${tag}" "${new_value}"
	    fi
	done

        if [[ "${file}" != "${file/-hd.flac/.flac}" ]]
        then
	    cmd_exec mv "${file}" "${file/-hd.flac/.flac}"
        else
            echo_error "No '-hd' renmaming needed..."
        fi
    done
fi
