#!/bin/sh
# /etc/init.d/audio
#
### BEGIN INIT INFO
# Provides:          audio
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Default-Start:     5
# Default-Stop:      0 6
# Short-Description: startupcounter
# Description:       Records number of entries into each run level to $logdirectory
### END INIT INFO

AUDIO_RESET_N=33

#set -x

set_gpio()
{
	if [ ! -d /sys/class/gpio/gpio$1 ]; then
		echo $1 > /sys/class/gpio/export
		echo out > /sys/class/gpio/gpio$1/direction
	fi
	
	echo $2 > /sys/class/gpio/gpio$1/value
}

echo -1 > /sys/devices/soc0/sound.17/HiFi/pmdown_time

case "$1" in
  start)
 	set_gpio ${AUDIO_RESET_N} 0
	
	for i in {1..10} 
	do
		#play a sound to get the codec initalized, there is probably a cleaner way to prevent the "pop"
		/usr/bin/speaker-test --nperiods 2 --nloops 1 -t sine >> /dev/null
		STATE=`cat /sys/devices/soc0/sound.17/HiFi/dapm_widget | grep "PM State:" | awk -F': ' '{ print $2 }'`
		if [ "${STATE}" == "On" ]; then
			break;
		else
		   sleep 2
		fi
	done				

	set_gpio ${AUDIO_RESET_N} 1

	amixer set PCM 200
  ;;
  stop)
	set_gpio ${AUDIO_RESET_N} 0
  ;;
  reset)
	set_gpio ${AUDIO_RESET_N} 0
	set_gpio ${AUDIO_RESET_N} 1
  ;;
  *)
	echo "Usage /etc/init.d/audio [start|stop|reset]"
	exit -1
  ;;
esac

exit 0
