#!/bin/bash
#
origem=/media/
#
destino=/tmp/novo_mp3/
#
source ./cores
#
clear
#
if [[ -d ${destino} ]]; then
    echo -e "Diretorio de Destino$cbved Ja Existe!$cbbra"$cfim
    echo
else
    echo -e "Diretorio de Destino$cver Não Existe!$cbbra Criando.: $cbved${destino}"$cfim
    mkdir -p ${destino}
    echo
fi
#
cd ${origem}
#
IFS=$(echo -en "\n\b")
#
function msg {
    tmb=80
    msg1=$1
    tmh1=$((${#msg1} - $2)) # tamanho da msg -'n' caracteres da cor + 2 '#'
    if [[ $tm = 1 ]]; then
       tmb=$tmah
       tm=0
    elif [[ $tmh1 -gt $tmb  ]]; then
          tmb=$(($tmh1 + 2))
          tmah=$tmb
          tm=1
    fi
    #
    msi1_spaces=$(printf "%*s" $((($tmb - $tmh1)/2)) "") # espacos antes da msg
    msf1_spaces=$(printf "%*s" $(($tmb - ($tmh1 + ($tmb - $tmh1)/2)))"") # espacos depois da msg
    repetec=$bverde"$(printf '%.0s#' $(seq $tmb))"$cfim
    #
    if [[ -n $4 ]]; then
       msg2=$3
       tmh2=$((${#msg2} - $4))
       msi2_spaces=$(printf "%*s" $((($tmb - $tmh2)/2)) "")
       msf2_spaces=$(printf "%*s" $(($tmb - ($tmh2 + ($tmb - $tmh2)/2)))"")
    fi
    #
    if [[ $3 != 1 ]]; then # se $3 não tiver 1 mostra o #
       if [[ $5 != 1 ]]; then # se o $5 não tiver 1 mostra o #
          echo -e $repetec
       fi
    fi
    #
    echo -e $bverde"#$msi1_spaces$bamarelo$msg1$msf1_spaces$bverde#"
    #
    if [[ -n $4 ]]; then
       echo -e $bverde"#$msi2_spaces$bamarelo$msg2$msf2_spaces$bverde#"
    fi
    echo -e $repetec
}
for fp in *.mp2 *.mp3 *.aac *.ac3 *.m4a *.ogg *.wav; do
    if [[ -f ${fp} ]]; then
       msg1=$cbbra"Processando o Arquivo.: $cbbra'$cbcia${fp}$cbbra'"
       tmh1=30
       msg2=$cbbra"Verificando o Volume em ${cbved}dB${cbbra}! ${cbama}>>> AGUARDE <<<$cbbra"
       tmh2=38
       msg $msg1 $tmh1 $msg2 $tmh2
       DBLEVEL=$(ffmpeg -i ${fp} -af "volumedetect" -f null /dev/null 2>&1 | grep max_volume | awk -F': ' '{print $2}' | cut -d' ' -f1)
       if (( $(echo "${DBLEVEL} < 0" | bc -l) )); then
          if (( $(echo "${DBLEVEL} > -0.5" | bc -l) )); then
             msg=$cbama"Ja esta no Nivel $cbbra'${cbved}Aceitavel$cbbra'$cbama de -->$cbbra '${DBLEVEL}dB!'"
             tmh=46
             msg $msg $tmh 1
             echo
          else
             DB=$(echo "${DBLEVEL}" | cut -c 2-6)
             BITRATE=$(ffmpeg -i ${fp} 2>&1 | grep Audio | awk -F', ' '{print $5}' | cut -d' ' -f1)
             msg1=$cbama"Corrigindo o Volume --> $cbbra'$cver${fp}$cbbra'"
             tmh1=30
             msg2=$cbbra"Nivel de '${cbved}dB${cbbra}'.: $cver${DBLEVEL}"
             tmh2=30
             msg $msg1 $tmh1 $msg2 $tmh2 1
             sleep 2
             ffmpeg -y -i ${fp} -af "volume=${DB}dB" -c:a libmp3lame -ac 2 -b:a 128k -ar 44100 ${destino}${fp} > /dev/null 2>&1
             echo
          fi
       else
          msg=$cbama"Ja esta no Nivel de -->$cbbra '${DBLEVEL}dB!'"
          tmh=14
          msg $msg $tmh 1
          echo
       fi
    fi
done
