#!/bin/bash
# hprid
################################################################################
#
# script to prepare audio files for HPR shows
#
# input: mp3 or ogg file
# result: mp3, ogg in 44100 Hz, spx files 16000Hz with intro and outro
# provides 3 interactive checks for audio quality, intro and outro
#
################################################################################
# This file is part of the HPR Tool set
# 
# HPR Tool set is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# HPR Tool set 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 Affero General Public License for more details.
# 
# You should have received a copy of the GNU Affero General Public License
# along with HPR Tool set.  If not, see .
# http://www.gnu.org/licenses/agpl-3.0.html
# #########################################################################
################################################################################
#
# PREREQUISITS
# - current folder has to be writable
# - there should NOT be a temp.ogg or temp.mp3 file
# - intro.mp3 and outro.mp3 have to be present
# - IMPORTANT: sox compiled with mp3 support
#                see http://a0u.xanga.com/700438974/howto-soc-installation
#
#
# IMPORTANT
# Backup the files before feeding them to this script, no guarantees here
# Handling of .wav not yet tested, but it should work 
#
# code.cruncher, May 2011
# 
################################################################################
################################################################################
#
# TODO
# 
# test handling of wav files
# add play final files or open them in specific player(s)
# add handling of ID3 tags
# create html interface for standardized info gathering 
#
################################################################################
#============================================================
# Check input
usage="usage: $(basename $0 ) [ -i ] [ -o ] , -i to add intro and -o outro, fname is a file with audio for HPR"
CHANNELS="1"
ADDINTRO="n"
ADDOUTRO="n"
while getopts "io" opt; do
    case $opt in
        i )
            ADDINTRO="y"
            ;;
        o )
            ADDOUTRO="y"
            ;;
    esac
done
shift $(($OPTIND - 1))
# if not ${mediafile} return usage
if [ $# -lt 1 ]; then
  echo $usage
  exit 1
fi
mediafile=${1}
# test if file exists 
if [ ! -f "intro.flac" ]; then
  echo "sorry, file \"intro.flac\" does not exist"
  echo "To download it run the command:"
  echo "   wget http://hackerpublicradio.org/media/theme-music/intro.flac"
  exit 1
fi
if [ ! -f "outro.flac" ]; then
  echo "sorry, file \"outro.flac\" does not exist"
  echo "To download it run the command:"
  echo "   wget http://hackerpublicradio.org/media/theme-music/outro.flac"
  exit 1
fi
for mediafile in "$@"
do
    echo $var   
    if [ ! -f "${mediafile}" ]; then
        echo "sorry, file \"${mediafile}\" does not exist"
        continue
    fi
    # test if file exists 
    if [ ! -r "${mediafile}" ]; then
        echo "sorry, file \"${mediafile}\" is not readable"
        continue
    fi
    if [ $(ffprobe "${mediafile}" 2>&1 | grep "Audio:" | wc -l ) -eq 0 ]; then
        echo "sorry, file \"${mediafile}\" has no audio track"
        continue
    fi
    # extract file name and extension
    fname=${mediafile%.*}
    ext=${mediafile/*./}
    #Make a backup
    # mediafilebackup=${mediafile}_$(md5sum ${mediafile} | cut -c -32 )_orig.${ext}
    # cp -v ${mediafile} ${mediafilebackup}
    # 
    # if [[ ! -e ${mediafilebackup} ]]; then
    #   echo "Backup not made: ${mediafilebackup}"
    #   exit
    # fi
    # check audio quality
    dur=7			# playtime of sample in seconds
    go=1			# variable to repeat playing of sample
    from=180                # start sample at 3 minutes in
    #============================================================
    # Question Time
    # # # while [ $go -ne 0 ]
    # # # do
    # # #   echo
    # # #   echo "--------------------------------------------------------------------------------"
    # # #   echo "1/4 AUDIO TEST: check audio quality: ... playing $dur seconds ..." 
    # # #   play "${mediafile}" trim $from $dur
    # # #   ((from+=180))           # next sample will be 3 minutes later
    # # #   read -s -n1 -p "sound quality ok?[y,n] ... or play another sample[a] ... [y,n,a]"
    # # #   echo
    # # #   case "$REPLY" in
    # # #     n) echo "aborting ... get better quality sound file ... good bye!"; exit 0;;
    # # #     y) go=0;;
    # # #   esac
    # # # done
    # # # 
    # # # # Check for intro
    # # # echo
    # # # echo "--------------------------------------------------------------------------------"
    # # # echo "2/4 ADDINTRO TEST: Is the intro playing? "
    # # # play "${mediafile}" trim 1 5	# play 5 seconds at beginning of file
    # # # read -s -n1 -p "Is there a intro? [y, n]" -i "n"; echo
    # # # if [ "$REPLY" = 'y' ]; then
    # # #   echo "Will add the intro"
    # # #   ADDINTRO="y"
    # # # fi
    # # # 
    # # # # Check for outro
    # # # echo 
    # # # echo "--------------------------------------------------------------------------------"
    # # # echo "3/4 ADDOUTRO TEST: Is the outro playing? "
    # # # len=$(eval "soxi -D \"${mediafile}\"")
    # # # len=$(echo "scale=0; $len - 50" | bc)
    # # # play "${mediafile}" trim $len 5
    # # # read -s -n1 -p "Is there a outro ? [y, n]" -i "n"; echo
    # # # if [ "$REPLY" = 'y' ]; then
    # # #   echo "Will add the outro"
    # # #   ADDOUTRO="y"
    # # # fi
    # # # 
    # # # 
    # # # echo
    # # # echo "--------------------------------------------------------------------------------"
    # # # echo "4/4 STEREO TEST: Should this be mono or stereo [m,s] ? "
    # # # CHANNELS="1"
    # # # read -s -n1 -p "intro ok? [m, s]" -i "m" ; echo
    # # # if [ "$REPLY" = 's' ]; then
    # # #   echo "Will convert to stereo"
    # # #   CHANNELS="2"
    # # # fi
    #============================================================
    # Preprocess the source file
    echo "Convert from ${mediafile} to known wav format ${fname}_tmp.wav"
    ffmpeg -i ${mediafile} -ar 44100 -ac $CHANNELS ${fname}_tmp.wav > ${fname}_tmp.log 2>&1
    # echo "Normalising the audio"
    # normalize -a 0.5 ${fname}_tmp.wav >> ${fname}_tmp.log 2>&1
    # TODO Compressor !
    # TODO add a little speed up
    # TODO little overlap in fade in of intro
    # echo "Truncating the silence"
    # sox ${fname}_tmp.wav ${fname}_sox.wav silence -l 1 0.1 1.6% -1 0.6 1.6% >> ${fname}_tmp.log 2>&1
    cp -v  ${fname}_tmp.wav ${fname}_sox.wav
    echo "Add the intro if it is missing and add it to the temp pcm file"
    if [ "$ADDINTRO" = 'y' ]; then
    ffmpeg -i intro.flac -ar 44100 -ac $CHANNELS -acodec pcm_s16le -f s16le - > ${fname}_tmp.pcm 2>> ${fname}_tmp.log 
    fi
    echo "convert the uploaded episode and add it to the temp pcm file"
    ffmpeg -i ${fname}_sox.wav -ar 44100 -ac $CHANNELS -acodec pcm_s16le -f s16le - >> ${fname}_tmp.pcm 2>> ${fname}_tmp.log 
    echo "Add the outro if it is missing and add it to the temp pcm file"
    if [ "$ADDOUTRO" = 'y' ]; then
    ffmpeg -i outro.flac -ar 44100 -ac $CHANNELS -acodec pcm_s16le -f s16le - >> ${fname}_tmp.pcm 2>> ${fname}_tmp.log 
    fi
    echo "Convert the pcm file to a know wav format"
    ffmpeg -f s16le -ar 44100 -ac 1 -acodec pcm_s16le -i ${fname}_tmp.pcm ${fname}_mez.wav 2>> ${fname}_tmp.log 
    # echo "Get an image of the converted audio"
    # sox ${fname}_mez.wav -n  spectrogram -x 800 -y 100 -o ${fname}_mez.png
    echo "--------------------------------------------------------------------------------"
    echo "File information"
    ffprobe ${fname}_mez.wav 2>&1 | grep Audio:
    mediainfo ${fname}_mez.wav
    echo "--------------------------------------------------------------------------------"
    # display ${fname}_mez.png &
    # read -s -n1 -p "Spectrogram check: Everything look ok [y,n] ? " -i "y" ; echo
    # if [ "$REPLY" = 'n' ]; then
    #   echo "Something went w  rong. Aborting."
    #   exit
    # fi
    # echo "--------------------------------------------------------------------------------"
    # vlc ${fname}_mez.wav >> ${fname}_tmp.log 2>&1 &
    # read -s -n1 -p "VLC check: Everything look ok [y,n] ? " -i "y" ; echo
    # if [ "$REPLY" = 'n' ]; then
    #   echo "Something went wrong. Aborting."
    #   exit
    # fi
    echo "Remove temp files"
    rm -v ${fname}_tmp.wav ${fname}_sox.wav ${fname}_tmp.pcm ${fname}_tmp.log
    echo "Convert to mp3" # TODO and add tags"
    sox -S ${fname}_mez.wav ${fname}_mez.mp3 
    echo "Convert to ogg" # TODO and add tags"
    sox -S ${fname}_mez.wav ${fname}_mez.ogg
    echo "Convert to spx" # TODO and add tags"
    sox -S ${fname}_mez.wav -c 1 -r 16000 -t wav  - | speexenc - ${fname}_mez.spx
    echo "Changing the file dates to the time of upload"
    touch -r ${mediafile} ${fname}*
done