#!/bin/bash
#-----------------------------------------------------------------------------------------------------------------------------------
#
# Music Tag Cleaner
#
# 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="music_tag_cleaner"
declare -g             HELP="usage: [-h | --help] | [-V | --version] | [-T | --test] [-v | --verbose] [-f | --fix_missing_album_artist] [-a | --default_artist <default_artist>] [-p | --music_pattern <music_pattern>] [-r | --root_dir <music_root_dir>]"

declare -g          ROOT_DIR="/opt/music/src"
declare -g    MUSIC_PATTERN="/"
declare -g   DEFAULT_ARTIST=""
declare -g          FIX_MAA="FALSE"

declare -g             MODE="DEFAULT"
declare -g          VERBOSE="FALSE"
declare -g          DRY_RUN="FALSE"





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

mtc_version_print()
{
    version_print
}





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

mtc_help_print()
{
    mtc_version_print
    help_print
}





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

mtc_args_parse()
{
    tmp_args=$(getopt -o r:p:a:ThVvf --long root_dir:,music_pattern:,default_artist:,test,help,version,verbose,fix_missing_album_artist -n "${NAME}" -- "$@")

    if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

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

    while true
    do
	case "$1" in
	    # Options
            -r|--root_dir)                        shift;       ROOT_DIR="$1";                      shift;;
            -p|--music_pattern)                   shift;  MUSIC_PATTERN="$1";                      shift;;
            -a|--default_artist)                  shift; DEFAULT_ARTIST="$1";                      shift;;

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

	    # Global options
            -f|--fix_missing_album_artist)                      FIX_MAA="TRUE";                    shift;;
            -v|--verbose)                                       VERBOSE="TRUE";                    shift;;

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





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

mtc_args_parse "$@"



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



echo_error "${NAME}: Mode: [${MODE}]   Verbose: [${VERBOSE}]   Root_Dir: [${ROOT_DIR}]   Music_Pattern: [${MUSIC_PATTERN}]   Fix_MAA: [${FIX_MAA}]   Default_Artist: [${DEFAULT_ARTIST}]"

if [[ ! -d "${ROOT_DIR}" ]]
then
    echo_error "Root directory doesn't exist !"
    exit -1
fi

i=1

while read -r track_file
do
    mt_tagtab_alloc

    mt_tagtab_read "0" "${track_file}" "DEFAULT"

    for tag in DISCTOTAL DISCNUMBER
    do
	if [[ "$(mt_tag_exist "${tag}")" != "" ]]
	then
	    echo_line "${track_file}: Cleaning '${tag}' Tag...\n" "${i}"
	    mt_tag_delete "${track_file}" "${tag}"
	fi
    done

    if [[ "$(mt_tag_exist "ALBUM ARTIST")" != "" ]]
    then
	if [[ "$(mt_tag_exist "ALBUMARTIST")" == "" ]]
	then
	    echo_line "${track_file}: Copying 'ALBUM ARTIST' into 'ALBUMARTIST' Tag...\n" "${i}"
            
            mt_tag_get album_artist 0 "ALBUM ARTIST"
	    mt_tag_write "${track_file}" "ALBUMARTIST" "${album_artist}"
	fi

	echo_line "${track_file}: Cleaning 'ALBUM ARTIST' Tag...\n" "${i}"
	mt_tag_delete "${track_file}" "ALBUM ARTIST"
    else
	if [[ "$(mt_tag_exist "ALBUMARTIST")" == "" ]]
	then
	    echo_line "${track_file}: Missing 'ALBUMARTIST' and 'ALBUM ARTIST' Tag...\n" "${i}"

	    if [[ "${FIX_MAA}" == "TRUE" ]]
	    then
		artist=""

		if [[ "${DEFAULT_ARTIST}" != "" ]]
		then
		    artist="${DEFAULT_ARTIST}"
		else
		    album_type=$(mt_album_type_get "${track_file}")

		    if [[ "/various_artists/tribute/original_soundtrack/child/" == */${album_type}/* ]]
		    then
			artist="Various Artists"
		    else
			if [[ "$(mt_tag_exist "ARTIST")" == "" ]]
			then
			    echo_line "${track_file}: Warning: Missing 'ARTIST' Tag...\n" "${i}"
			else
                            mt_tag_get artist 0 "ARTIST"
			fi
		    fi
		fi

		if [[ "${artist}" != "" ]]
		then
		    echo_line "${track_file}: Copying '${artist}' into 'ALBUMARTIST' Tag...\n" "${i}"
		    mt_tag_write "${track_file}" "ALBUMARTIST" "${artist}"
		fi
	    fi
	fi
    fi

    if [[ "${track_file##*.}" == "flac" ]]
    then
	if [[ "$(file "${track_file}" | grep ID3)" != "" ]]
	then
	    echo_line "${track_file}: Cleaning Flac ID3 Tags...\n" "${i}"
	    mt_tag_all_delete "${track_file}" "id3"
	fi
    fi

    echo_line "${track_file}: OK\r" "${i}"

    i=$(( i + 1 ))
done < <(find "${ROOT_DIR}" \( -name '*.flac' -o -name '*.mp3' \) | grep -e "${MUSIC_PATTERN}" | sort)

echo_line ""
