#!/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
#       }}}
#
+--- 12 lignes : TODO : --------------------------------------------------------------------------------
#
# $ 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 {{{

+--- 18 lignes : function usage_script() ----------------------------------------------------------------

# 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

  #############################
+---- 18 lignes : # Option d'exécution de vlc ----------------------------------------------------------
  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

+--  4 lignes : Special command for Vim editing modelines, (not mandatory) ------------------------------