#!/bin/sh 
# 
# {{{ Script Header
#
# SCRIPT : {{{
#
#	radiorecord.sh [ -h ] | -r <radio> -u <url> -t <durée> -d <répertoire>
#
#	OPTIONS
#
#		 -r <radio>  → nom de la radio enregistrée
#		 -u <url>    → URL de la playlist à télécharger en stream
#		 -t <durée>  → durée de l'enregitrement en secondes
#		 -d <rép.>   → répertoire
#		 -h          →  affiche l'aide
#
#	Code d'erreur :
#		 0 
#		65 mauvais appel du script, options manquantes ou en surnombre (E_OPTIONS)
#		66 erreur lors de l'appel de vcl, enregistrement vide, radion injoignable… (E_VLC)
#
#	DOC :
#			vlc :
#		[0] http://wiki.videolan.org/VLC_command-line_help
#		[1] http://wiki.videolan.org/VLC-0-8-6_command-line_help
#		[2] http://www.videolan.org/doc/streaming-howto/fr
#
#			BASH :
#		[3] http://abs.traduc.org/abs-5.3-fr/
#			- commandes find http://abs.traduc.org/abs-5.3-fr/ch03.html#ex58
#	}}}
#
# TODO :	{{{
#	use getops to sort out options (bash only?)
#	use "grep -P ppid vlc" instead of ps command (and simplify test?)
#	how to handle sound format for different stream?
#	in case of dump vlc options choice, adding SOUND_FORMAT might be useful
#	test availability of the stream
#	Is directory existing (-d <dir>)?
#	Complete english transaltion for all coments
#	FIXED => clean up code & test lines, add debug lines <=
#	FIXED => what about vlc log file? <= version 0.9.6
#	DONE => move version paragraph > changelog
#	}}}
#
# $ version 0.9.10 $ $ date 2009/03/08 $
#
#   COPYRIGHT {{{
#   Copyright (c) 2008-2009 by Tortuga Team <efrim@azylum.org>
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License.
#
#    This program 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 General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#    }}}
# }}}

#set +b

DEBUG=${DEBUG:-"0"}	#  Set to 1 in order to enable DEBUG message.
			## Use "export DEBUG=1" in the calling script to enable it
			## Only error message will be printed with DEBUG="0"

LOCK=/tmp/lock-radiorecord-$$
:>$LOCK
SCRIPT_PID=$$

E_OPTIONS=65
E_VLC=66

# FUNCTIONS DEFINITIONS {{{

function usage_script()	# {{{
{
    nom_script=$(basename $0 .sh)
echo "
SYNOPSIS
	$nom_script [ -h ] | -r <radio> -u <url> -t <durée> -d <répertoire>

OPTIONS
	 -r <radio>  → nom de la radio enregistrée
	 -u <url>    → URL de la playlist à télécharger en stream
	 -t <durée>  → durée de l'enregitrement en secondes
	 -d <rép.>   → répertoire
	 -h          → affiche l'aide

DESCRIPTION
	[...] yet to come
"
}	# }}}

# Record Function
function Record() # {{{
{
	vlc $URI $OPTIONS_VLC & PIDVLC=$!
	echo $PIDVLC > $LOCK
	[[ $DEBUG -eq "1" ]] && echo "${RECORDER}'s pid: $PIDVLC"
	#
	echo "${RADIO//_/ } : $(date)" > ${TXT_FILE}
	# Ajout d'une autre date au format standard RFC
	echo "$(date -R)" >> ${TXT_FILE}
}	# }}}

# }}} END DEFINITIONS

# Contrôle le nombre d'argument {{{
NB_ARGIN=8
if [ "$1" == "-h" ];then
	usage_script;
	exit 0
elif [ $# -ne $NB_ARGIN ];then
	/bin/echo -e "Options maquantes, incomplètes ou en surnombre\n";
	usage_script;
	exit $E_OPTIONS;
fi # }}}

# {{{ GETOPTS
while [ -n "$1" ]
do
	case "$1" in
	"") usage_script ; exit 0 ;;
	-r) RADIO="${2// /_}" ; shift 2;;
	-u) URI="$2" ; shift 2;;
	-t) DUREE="$2" ; shift 2;;
	-d) DIR="$2" ; shift 2;;
	esac
done
# }}}

## D'autres variables {{{
#####################
## {{{
  RECORDER=/usr/bin/vlc
  #SOUND_FORMAT="mp3"
  #File prefix
  PREFIX="$(date +%y%m%d_%Hh%M)"
  #Output directories
  RECORD_FILE="${DIR}/${RADIO}-${PREFIX}.mp3"
  TXT_FILE="${DIR}/${RADIO}-${PREFIX}.txt"
  LOG_FILE="${DIR}/${RADIO}-${PREFIX}.log"
  # write file naming to temporary file
  echo "${RADIO}-${PREFIX}" > ${DIR}/name.radiorecord

  #############################
  ## Option d'exécution de vlc {{{
  # Un paquet de jeux d'options différentes, c'est plutôt toufu vlc :/
  # Seul la dernière semble utile.
  #
  # Wave file
  #OPTIONS_VLC="--aout aout_file --logfile $LOG_FILE --logmode text\
  #             --verbose 1 --no-video -I dummy\
  #             --no-interact --audiofile-file $RECORD_FILE"

  # Ogg File transcode
  #OPTIONS_VLC="-I dummy --sout file/ogg:$RECORD_FILE"

  # DUMP ?
  # remplacer « access » par « append » pour ajouter à un fichier.
  # les deux lignes suivante sont équivalentes, scriptées elles posent un probléme.
  #OPTIONS_VLC="-I dummy --sout \"#std{access=file,mux=dummy,dst=\"$RECORD_FILE\"}\""
  #OPTIONS_VLC="-I dummy --no-audio --sout-standard-access=file --sout-standard-mux=dummy --sout-standard-dst=\"$RECORD_FILE\"}"
  # }}}
  OPTIONS_VLC="-R -I dummy --sout file/dummy:$RECORD_FILE --file-logging --logfile ${LOG_FILE}"
  #
  ##

## }}}
##################### }}}

# debug echo
[[ $DEBUG -eq "1" ]] &&  echo "Exécution de l'enregistrement vlc : $(date +%s) s"

# Lance l'enregistrement
Record

# termine l'exécution du script si vlc ne tourne pas
ps --pid $PIDVLC > /dev/null;
if [ $? -ne 0 ];then
	rm -rf $LOCK
	exit $E_VLC
fi

# wait for $DUREE seconds
sleep ${DUREE}s

# debogue echo
[[ $DEBUG -eq "1" ]] && echo "Termine l'exécution de vlc : $(date +%s) s"

# Met fin à l'enregistrement
kill -15 $PIDVLC
sleep 2s
# Enregistrement vraiment terminé ?
ps --pid $PIDVLC > /dev/null; CDR=$?
if [ $CDR -ne 1 ]
then
	echo "Process vlc still alive, sending SIGKILL signal."
	kill -9 $PIDVLC
fi

#Écrit les erreurs potentielles de l'enregistrement dans le journal
ERROR_PATT="(error|disconnected)"
ERROR_MESS=$(grep -E "$ERROR_PATT" "${LOG_FILE}")
echo -e "Some errors occur during recording:\n${ERROR_MESS}\n"| sort -u >> ${TXT_FILE}

rm -rf $LOCK

exit 0

# Special command for Vim editing modelines, (not mandatory) {{{
# vim: encoding=utf8 autoindent nowrap nolist fo=rcqo fdl=1 fdm=marker
# }}}

