#!/bin/bash

# Title......: mp4tomp3
# Description: wrapper to convert movie files to audio
# Author.....: Mitchell Johnston - uid 0
# Contact....: johnstonm401@gmail.com
# Updated....: Fri 16 Sep 2022 03:14:48 AM CDT
#----------------------------------

# notes
#----------------------------------

# variables
#----------------------------------
[ "$1" == "-D" ] && DEBUG=1 && shift 1     # -D to turn on debug mode
PS4='$SECONDS $LINENO: '                   # debug prompt
DOW=$(date +%a)                            # day of week: Thu
TODAY=$(date +%m/%d)                       # month/day: 03/25
DOM=$(date +%d)                            # day of month: 25
OS=$(uname -s)                             # OS type: SunOS Linux
NAME=${0##*/}                              # name of the script

# functions
#----------------------------------
bl(){ ## write a blank line
    # Use: bl
    [ "$DEBUG" == "1" ] && set -x
    echo ""
}

html(){ ## mark up code
    vim -f +"syn on" +"set nonu" +"set foldenable!" +"set nospell" +"run! syntax/2html.vim" +"wq" +"q" $1
}

log(){ ## creates a basic log entry $LOG must be defined
    # Use: log {entry}  
    [ "$DEBUG" == "1" ] && set -x
    logger -i -t "$NAME" "$*"
}

pause(){ ## simple pause routine
    # Use: pause  {optional number of seconds} or "-nt" for no time out 
    [ "$DEBUG" == "1" ] && set -x
    [ "$1" == "-nt" ] && TMOUT="" && shift
    echo "$BY";
    if [ $# -gt 0 ]
    then
        read -t $1 -r -p "${C}Hit any key (${BY}$1${C} second timeout)${N}" -n 1 FOO;
    else
        read -r -p "${C}Hit any key${N}" -n 1 FOO;
    fi;
    bl
}

xtitle(){ ## set window title
    # Use: xtitle "Text to display"
    printf "\033]0;%s\007" "$*"
}

# setup
#----------------------------------

# this provides a quick way to edit all my scripts on the fly
if [ "$1" == "-E" ]
then
    vim $0
    sed -i -e "7s/.*/# Updated....: $(date)/" $0
    log "Updated $0"
    html $0
    cp $0 /var/www/unix
    mv $0.html /var/www/unix
    cp $0 /var/gopher/bin
    exit
fi

# display help if needed
if [ "$1" == "-h" ] || [ "$1" == "--help" ]
then
fmt -s -w $(tput cols) <<END
$NAME  {files}

Converts mp4 files to mp3 files, removes source when completed and also does volume leveling.

END
exit
fi

# listing of required apps
command -v bash >/dev/null || sudo apt install bash -qyy
command -v ffmpeg >/dev/null || sudo apt install ffmpeg -yyq
command -v normalize-audio >/dev/null || sudo apt install normalize-audio -yyq

# main
#--------------------------- 
[ "$DEBUG" == "1" ] && set -x

TC=$(ls -l *mp4 *webm|wc -l)
CC=1
for FILE in "$@"
do
    xtitle "Converting: $CC of $TC"
    let "CC = CC + 1"
    NAME=$(echo $FILE|cut -d'.' -f1)
    echo "${BG}Converting:${BY} ${NAME}${N}"
    ffmpeg -y -v 8 -stats -i $FILE $NAME.mp3 && \rm $FILE
done
which normalize-audio >/dev/null && normalize-audio -bv *.mp3
lm