#!/bin/bash


# Reset
RESET='\033[0m'       # Text Reset

# Regular Colors
Black='\033[0;30m'        # Black
Red='\033[0;31m'          # Red
Green='\033[0;32m'        # Green
Yellow='\033[0;33m'       # Yellow
Blue='\033[0;34m'         # Blue
Purple='\033[0;35m'       # Purple
Cyan='\033[0;36m'         # Cyan
White='\033[0;37m'        # White

# Bold
BBlack='\033[1;30m'       # Black
BRed='\033[1;31m'         # Red
BGreen='\033[1;32m'       # Green
BYellow='\033[1;33m'      # Yellow
BBlue='\033[1;34m'        # Blue
BPurple='\033[1;35m'      # Purple
BCyan='\033[1;36m'        # Cyan
BWhite='\033[1;37m'       # White


# Set recording file path
recording_dir="/var/spool/asterisk/monitor"
auto_delete_failed=0
declare -i failed_convertion
declare -i empty_files
declare -i exit_needed
declare -i process_is_done
declare -i total_wav
declare -i total_mp3
declare -i total_savings
declare -i sofarsogood


failed_convertion=0
empty_files=0
process_is_done=0
exit_needed=0
total_wav=0
total_mp3=0
total_savings=0
total_savings_percent=0
sofarsogood=0

function ctrl_c() {
    echo ""
    exit_needed=1
    echo -e "${BRed}Shutting Down MP3 Conversion${RESET}"
}

#  ALTER TABLE `cdr` ADD INDEX `recordingfile` (`recordingfile`);
#trap ctrl_c INT
#trap ctrl_c SIGTERM
trap ctrl_c SIGINT
#trap ctrl_c SIGFPE
#trap ctrl_c SIGKILL
#trap ctrl_c SIGHUP

function get_totals() {
        #echo "calculating totals"
        #echo "1: wav ${1}"
        #echo "2: mp3 ${2}"
        total_wav=$(( ${total_wav} + ${1} ))
        total_mp3=$(( ${total_mp3} + ${2} ))
        #total_savings=$((${total_wav} - ${total_mp3} ))
        total_savings=$(echo "scale=4; ${total_wav} - ${total_mp3}" | bc )
        total_savings_percent=$(echo "scale=2; 100*${total_savings} / ${total_wav}" | bc )
        #echo "Total wav ${total_wav}"
        #echo "Total MP3 ${total_mp3}"
        #echo "Total Saved ${total_savings_percent}%"

}

function print_totals() {
        echo "Total Wav files size $(get_human ${total_wav})"
        echo "Total MP3 files size $(get_human ${total_mp3})"
        echo "Total size savings $(get_human ${total_savings})"
        echo "Total Saved ${total_savings_percent}%"

}


function bytestohuman() {
    # converts a byte count to a human readable format in IEC binary notation (base-1024), rounded to two decimal places for anything larger than a byte. switchable to padded format and base-1000 if desired.
    local L_BYTES="${1:-0}"
    local L_PAD="${2:-no}"
    local L_BASE="${3:-1024}"
    BYTESTOHUMAN_RESULT=$(awk -v bytes="${L_BYTES}" -v pad="${L_PAD}" -v base="${L_BASE}" 'function human(x, pad, base) {
         if(base!=1024)base=1000
         basesuf=(base==1024)?"B":"B"

         s="BKMGTEPYZ"
         while (x>=base && length(s)>1)
               {x/=base; s=substr(s,2)}
         s=substr(s,1,1)

         xf=(pad=="yes") ? ((s=="B")?"%5d   ":"%8.2f") : ((s=="B")?"%d":"%.2f")
         s=(s!="B") ? (s basesuf) : ((pad=="no") ? s : ((basesuf=="iB")?(s "  "):(s " ")))

         return sprintf( (xf " %s\n"), x, s)
      }
      BEGIN{print human(bytes, pad, base)}')
    return $?
}

function get_human()
{
        bytestohuman $1
        echo "${BYTESTOHUMAN_RESULT}";
}


# find /var/spool/asterisk/monitor -printf '%u:%g\n' | sort -t: -u

# find /var/spool/asterisk/monitor -size 0 -type f -name "*.wav"
# find /var/spool/asterisk/monitor -type f -name "*.wav"

# start loop
for wav_file in $(find $recording_dir -type f -name "*.wav" | sort -n); do

        if [[ ${exit_needed} -eq 1 ]]; then
                process_is_done=1
                for i in $(seq 10); do
                        echo -ne "${BRed}.${RESET}"
                        sleep 0.5
                done
                echo
                break
        fi

        wav_filepath="$(echo $wav_file | sed 's/.*\///')"
        mp3_file="$(echo $wav_file | sed s/".wav"/".mp3"/)"

        mp3_filepath="$(echo $mp3_file | sed 's/.*\///')"

        wav_size=$(ls -lah $wav_file | awk '{ print $5}')
        wav_byte_size=$(du -sb --apparent-size $wav_file | awk '{print $1}')

        if [[ $wav_byte_size -eq 44 ]]; then
                echo $wav_file
                echo -e "${BRed}File is 44 Bytes long, indicating empty audio file, we should delete it\nSkipping---${RESET}"
                continue
        fi

        if [[ $wav_byte_size -eq 0 ]]; then
                echo $wav_file
                echo -e "${BRed}File is 0 Bytes long, indicating empty audio file, we should delete it\nSkipping---${RESET}"
                continue
        fi

        echo
        echo -e "${BYellow}WAV file size ${wav_size}${RESET}"



        # convert to MP3
        #nice lame -b 16 -m m -q 9 --verbose "$wav_file" "$mp3_file" && {
        #nice lame -b 8 -m m -q 9 --resample 8 --replaygain-fast --clipdetect --verbose "$wav_file" "$mp3_file" && {
        #nice lame -m m -q 8 --resample 8 --verbose "$wav_file" "$mp3_file" && {
        #nice lame -b 16 -m m -q 8-resample --verbose "$wav_file" "$mp3_file" && {
        #nice lame -V 9.9 -m m -q 8-resample --verbose "$wav_file" "$mp3_file" && {
        #nice lame -V 9.9999 -m m --verbose "$wav_file" "$mp3_file" && {
        nice lame -V9.99 -m m "$wav_file" "$mp3_file" && {
                        echo
                        mp3_size=$(ls -lah $mp3_file | awk '{ print $5}')
                        mp3_byte_size=$(du -sb --apparent-size $mp3_file | awk '{print $1}')
                        #echo "Removing File $wav_file"
                        #stat --format=%s $mp3_file

                        echo -e "${BGreen}New MP3 file size ${mp3_size}${RESET}"
                        get_totals $wav_byte_size $mp3_byte_size
                        chown asterisk:asterisk $mp3_file
                        sofarsogood=1
                        # Update DB
                        mysql -u root -s -N -D asteriskcdrdb<<<"UPDATE cdr SET recordingfile='$mp3_filepath' WHERE recordingfile = '$wav_filepath'" || sofarsogood=0
                        if [[ $sofarsogood -eq 1 ]]; then
                                rm -frv $wav_file
                        else
                                echo -e "${BRed}Failed to update database${RESET}"
                        fi

                } || {
                        echo -e "${BRed}${wav_file} encoding failed"
                        echo -e "$failed_convertion Failed${RESET}"
                        failed_convertion+=1
                        # Update DB
                        if [[ "$auto_delete_failed" -eq 1 ]]; then
                                echo "Deleting failed recording..."
                                #exit 1
                                #mysql -u root -s -N -D asteriskcdrdb<<<"UPDATE cdr SET recordingfile='$mp3_filepath' WHERE recordingfile = '$wav_filepath'" || echo "Failed to update database"
                        else
                                echo "Auto Delete Disabled"
                        fi
                }


        echo -e "${BGreen}Resized recording from ${wav_size} wav to ${mp3_size} MP3 Audio${RESET}"
        echo "-------------------------------------------------------"

        #echo "Wav File : " $wav_file
        #echo "Wav No Path : " $wav_filepath
        #echo "MP3 File : " $mp3_file
        #echo "MP3 No Path : " $mp3_filepath
        #echo "End File ---------------------------------------------------"

        #exit 0

# End of loop
done
print_totals
echo
echo "${failed_convertion} Failed to convert"
if [[ ${empty_files} > 0 ]]; then;
    echo -e "${BRed}Found ${empty_files} Empty Recording Files (44 bytes)${RESET}"
fi
exit 0
