#!/bin/bash
#### 将指定目录中的录音合并,压缩成mp3
#### parameter ######
####$1: 目录的绝对路径(必填)
####$2: 空/AD/mp3 目标格式，为空时合并并压缩成IAMPCM格式(5K/S),AD:合并不压缩，保留ADPCM格式(15K/S),mp3:压缩成mp3格式
####$3  空/1 是否保留wav格式文件，$2为mp3时生效 ，设为1是，压缩成mp3后不删除原wav文件
####例：
####合并并压缩成mp3,不保留原wav文件
####./mixinout.sh /var/spool/asterisk/monitor/ mp3
####合并并压缩成IAMPCM
####./mixinout.sh /var/spool/asterisk/monitor/ 
####合并并压缩，保留ADPCM格式
####./mixinout.sh /var/spool/asterisk/monitor/ AD 

if [ "X$1" == "X" ];then
echo "incorrect parameter!"
exit;
fi
#
if [ ! -d "$1" ];then
echo "$1 is not a directory"
fi

#if [ ! -d "$3" ];then
#mkdir -p $3
#fi
for targetDir in `find $1 -type d -printf "%n %p\n" | grep '^2 '| cut -d " " -f 2`
do
    for infile in `find ${targetDir} |grep -E "[0-9]+\.wav|*-in\.wav"`
    do
        bsname=`basename $infile`
        fdir=${infile/$bsname/}
        bsname=`echo ${bsname} |cut -d. -f1`
        datestr=`echo ${bsname} |cut -d- -f1`
        callerstr=`echo ${bsname} |cut -d- -f2`
        calleestr=`echo ${bsname} |cut -d- -f3`
        #echo $calleestr;/var/spool/asterisk/monitor/1/2015/03/10/20150310165544-5001-9600-in.wav
        outfile="${fdir}${datestr}-${callerstr}-${calleestr}-out.wav"
        targetfile="${fdir}${datestr}-${callerstr}-${calleestr}.wav"
        echo "---------------";
        echo $infile
        echo $outfile
        echo "---------------";
        if [ -f $outfile ];then
            if [ "$2" == "AD" -o "$2" == "mp3" ];then
                echo "sox -m $infile $outfile -s $targetfile"
                sox -m $infile $outfile -s $targetfile
            else
                echo "sox -m $infile $outfile -i $targetfile"
                sox -m $infile $outfile -i $targetfile
            fi
            rm -f $infile $outfile
        else
            #targetfile="${fdir}${datestr}-${callerstr}-${calleestr}"
            echo "!!!!!!!!can not find outfile $outfile targetfile to $targetfile !!!!!!!!!!"
            if [ -f "$targetfile" -a "$2" == "mp3" ];then
                adtargetfile="${fdir}${datestr}-AD${callerstr}-${calleestr}.wav"
                echo "sox $targetfile -s $targetfile"
                sox $targetfile -s "$adtargetfile";
                mv -f "$adtargetfile" $targetfile
            fi
        fi

        if [ -f "$targetfile" -a "$2" == "mp3" ];then
            file=`echo $targetfile |cut -f1 -d.`
            fileformat=`echo $targetfile |cut -f2 -d.`
            if [ $fileformat == "wav" ];then
                echo "converting $targetfile to mp3";
                lame --cbr -m m -t -F $targetfile $file.mp3  >/dev/null 2>&1
                if [ "$3" != "1" -a -f "$file.mp3" ];then
                    rm -f $targetfile
                fi
            else
                echo "$targetfile is not a wav file";
            fi
        fi

    done
done
