#!/bin/bash
MYTH_RUN_STATUS="1"
. /etc/systemconfig
. /etc/profile
echo $@ >/tmp/audio.call

BASE=""
TESTFILE="/usr/share/sounds/pinkNoise_3s.wav"
OSSinstalled="false"

BLACKLIST=/etc/modprobe.d/soundconfig_blacklist.conf
. /usr/MythVantage/bin/install_functions.sh
home_check

echo "---------------------------------------"


function testaudio () {
    ossplay  -d$AUDIODEVICE $TESTFILE
}

function load_alsa() {
    echo "Loading ALSA ..."
    remove_service.sh alsa-utils 1> /dev/null 2> /dev/null

    echo "   uninstalling oss"
    pacman -R --noconfirm oss

    echo    "triggering udev module load"
    depmod -a
    udevadm settle
    udevadm trigger
    udevadm settle

    add_service.sh alsa-utils
}


function unload_alsa () {
    echo "unloading ALSA ..."
    #kill $(lsof -t /dev/dsp* /dev/audio* /dev/mixer* /dev/snd/*) && modprobe -r $(lsmod |grep ^snd |awk '{print $1}')
    sv stop alsa-utils
    remove_service.sh alsa-utils
    rm -rf /dev/adsp*
    rm -rf /dev/snd/*
    rm -rf /dev/audio
    remove_asound
    modprobe -r $(lsmod |grep ^snd |awk '{print $1}')
}

function unload_oss {
    echo "unloading OSS ..."
    sv stop oss
    soundoff
    rm -rf /dev/dsp*
    rm -rf /dev/oss*
    rm -rf /dev/sndstat
    remove_service.sh oss
    rm -f $BLACKLIST
}

function installOSS {
    echo "installing OSS ..."
    pacman -Q oss 2>/dev/null
    if [  ! $? = 0 ]
    then
        pacman --noconfirm -S --force oss
    fi
    soundon
    if [ ! $? = 0 ]
    then
        pacman --noconfirm -S --force gcc make binutils
        soundon
    fi
    add_service.sh oss
    echo "blacklist soundcore" > $BLACKLIST
    echo "install soundcore /bin/false" >> $BLACKLIST
}


function SYNCMPLAYER {
    echo "modify mplayer config file"
    if [ -f /etc/mplayer/mplayer.conf ]
    then
        backdate=`date +%b-%d-%Y-%H:%M:%S`
        mv /etc/mplayer/mplayer.conf /etc/mplayer/mplayer.conf-$backdate
    fi
    if [  x$AUDIOTYPE = xALSA  -o   x$AUDIOTYPE = xalsa ]
    then
        if [ "$mixAUDIODEVICE" ]
        then
            MPLAYERDEVICE="plug=dmixer"
        else
            MPLAYERDEVICE=`echo $AUDIODEVICE | tr : = | tr , .`
        fi
        echo "ao=alsa:device=$MPLAYERDEVICE" > /etc/mplayer/mplayer.conf
        echo "ac=hwac3,hwdts," >> /etc/mplayer/mplayer.conf
    else
        echo "ao=oss:$AUDIODEVICE" > /etc/mplayer/mplayer.conf
    fi
}

function checkOSSinstalled () {
    echo "Checking if OSS is installed"
    ossinfo |grep Version |grep -q OSS >/dev/null
    resultcode=$?

    if [ $resultcode = 0 ]
    then
        OSSinstalled='true'
        echo "   OSS is loaded"
    else
        OSSinstalled='false'
        echo "   OSS is NOT loaded"
    fi
}

function backup_asound {
    echo "backup asound.conf file"
    if [ -f /etc/asound.conf ]
    then
        backdate=`date +%b-%d-%Y-%H:%M:%S`
        mv /etc/asound.conf /etc/asound.conf-$backdate
    fi
}

function remove_asound {
    echo "removing asound.conf file"
    backup_asound
}

function write_asound {
    echo "writing asound.conf file"
    backup_asound
    mixAUDIODEVICE=""
    if [[ $AUDIODEVICE == plughw:* ]]
    then
        mixAUDIODEVICE=`echo $AUDIODEVICE | sed 's/plughw:\(.\)/\1/g'`
        echo 'pcm.dmixer {
  type dmix
  ipc_key 2048
  slave {
    pcm "hw:'"$mixAUDIODEVICE"'"
    period_size 512
    buffer_size 4096
  }
}

pcm.!default {
  type plug
  slave.pcm "dmixer"
}' > /etc/asound.conf
    else
    	echo 'pcm.!default "'"$AUDIODEVICE"'"' > /etc/asound.conf
    fi
}

function sound_config_system {
    if [  x$AUDIOTYPE = xALSA  -o   x$AUDIOTYPE = xalsa ]
        then
        write_asound
    fi
    SYNCMPLAYER
}

function loadsound (){
    checkOSSinstalled
    if [  x$AUDIOTYPE = xOSS  -o   x$AUDIOTYPE = xoss ]
        then
        i=1
        while [[ $OSSinstalled = "false" && $i -le 20 ]]
        do
            unload_alsa
            if [ -e /tmp/.alsatest ]
            then
                rm /tmp/.alsatest
            fi
            installOSS
            checkOSSinstalled
            i=$(( $i + 1 ))
        done
    else
        touch /tmp/.alsatest
        unload_oss
        load_alsa
        rm /tmp/.alsatest
    fi
}




#####################MAIN PROGRAM##########################

declare -r OPTSTRING="i:t:d:"

if [ $# -eq 0 ]
then
    echo "Valid options are:"
    echo "  -i  (oss|alsa)   oss or alsa subsystem  "
    echo "  -t  (test|real|LOAD)   "
    echo "  -d device"
    exit 1
fi




while getopts "$OPTSTRING"  SWITCH
do
    case $SWITCH in
        \?)  echo "unknown option"
            exit 11
        ;;
        i) #echo "$SWITCH"  "$OPTARG"
            AUDIOTYPE="$OPTARG"
        ;;
        d) #echo "$SWITCH"  "$OPTARG"
            AUDIODEVICE=$OPTARG
        ;;
        t) #echo "$SWITCH"  "$OPTARG"
            SOUNDOPTYPE="$OPTARG"
            if  [ x"$OPTARG" = xtest ]
            then
                TEST=true
            else
                TEST=false
            fi
        ;;
    esac
done



case $SOUNDOPTYPE in
    REAL|real )
        #loadsound
        sound_config_system
    ;;
    test|TEST)
        echo $@ > /tmp/audio.test

        #set iec958 audio bit
        if [[ $AUDIODEVICE == plughw:* ]]
        then
            cardName=`echo $AUDIODEVICE | sed 's/plughw:\(.*\),.*/\1/g'`
            #cardDevice=`echo $AUDIODEVICE | sed 's/.*,\(.*\)/\1/g'`
            iecset -c "$cardName" audio 1
        else
            cardName="0"
            iecset audio 1
        fi

        #unmute IEC958
        amixerControls=`amixer -c "$cardName" scontrols`
        while read -r line; do
            if [[ $line == *IEC958* ]]
            then
                amixCard=`echo "$line" | sed "s/.*\ \('.*\)/\1/g"`
                amixer -c "$cardName" sset "$amixCard" unmute
            fi
        done <<< "$amixerControls"

        #loadsound
        if [  x$AUDIOTYPE = xOSS  -o   x$AUDIOTYPE = xoss ]
        then
            echo "testing OSS  $AUDIODEVICE "
            ossplay  -d$AUDIODEVICE $TESTFILE
        else
            echo "testing ALSA $AUDIODEVICE "
            #echo aplay --device=$AUDIODEVICE $TESTFILE
            aplay --device=$AUDIODEVICE $TESTFILE
        fi
    ;;
    LOAD|load)
        loadsound
    ;;
esac

exit 0