#!/bin/bash
#
# audiologger - a little script to record mp3/ogg to your harddrive
#
# Copyright (C) 2004 Ilja Gerhardt <ilja@so36.de>
#
# This source code is free software; you can redistribute it and/or
# modify it under the terms of the GNU Public License as published 
# by the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version.
#
# This source code 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.
# Please refer to the GNU Public License for more details.
#
# You should have received a copy of the GNU Public License along with
# this source code; if not, write to:
# Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

# Global settings:
: ${DIALOG=dialog}
GENNAME="audiologger"
CHUNK="3600"
INFO_COMMENT="Recorded from /dev/dsp by StreamBOX"

# determine the IP-address of the localsystem
myip=`/sbin/ifconfig | grep inet | grep -v 127.0.0 | awk {'print $2;'} | sed s/.*://`

if [ "$myip" == "" ]
then
        myip="StreamBOX";
fi

# root werden...
[ "`id -u`" != "0" ] && exec sudo "$0" "$@"

stty -icanon min 0 time 1 cbreak

# subprogram record

audiorecord () {
	LENGTH=$1
	DATAPFAD=`/bin/date +%y%m%d`
	test -x $PFAD/$GENNAME/$DATAPFAD || mkdirhier $PFAD/$GENNAME/$DATAPFAD
	FILENAME=`/bin/date +%y%m%d_%H%M`
	INFO_TITLE=`/bin/date +%y%m%d_%H%M`
	INFO_YEAR=`/bin/date +%Y`
	INFO_DATE=`/bin/date +%d-%m-%Y`
	echo -e "\033[1;32mRecording $LENGTH seconds to file: $PFAD/$GENNAME/$DATAPFAD/$FILENAME.$TYPE\033[0m"
	echo -e "$M18"
	if (echo $TYPE | grep mp3 > /dev/null)
	then
	 rawrec -t $LENGTH |\
	 /usr/bin/lame\
	 --tt "$INFO_TITLE"\
	 --tc "$INFO_COMMENT"\
	 --ty "$INFO_YEAR"\
	 -h -a -b $BITRATE -m $MODE -x - - >\
	 $PFAD/$GENNAME/$DATAPFAD/$FILENAME.$TYPE
	else
	 if (echo $MODE | grep m > /dev/null)
	 then MIX="--downmix"
	 else
	 MIX=""
	 fi
	 rawrec -t $LENGTH |\
	 /usr/bin/oggenc\
	 -b $BITRATE $MIX\
	 -t "$INFO_TITLE"\
	 -c "comment=$INFO_COMMENT"\
	 -d "$INFO_DATE"\
	 --raw -q -1 - >\
	 $PFAD/$GENNAME/$DATAPFAD/$FILENAME.$TYPE
	fi
}

# subprogramm care for space

careforspace () {
	SPACELEFT=`df -m | grep $PFAD | awk {'print $4;'}`
	echo -e "\033[1;34mSpace left on disk: $SPACELEFT M - You wanted to have at least $MINLEFT M \033[0m"
	OLDFILE=`find $PFAD/$GENNAME/ -name "*.$TYPE" | sort | head --lines=1` 
	echo -e "\033[1;34mThe oldest file is: $OLDFILE\033[0m"
	while [ $SPACELEFT -lt $MINLEFT ]
	do
		echo -e "\033[1;31mDeleting old file $OLDFILE\033[0m"
		rm -f $OLDFILE
		SPACELEFT=`df -m | grep $PFAD | awk {'print $4;'}`
		OLDFILE=`find $PFAD/$GENNAME/ -name "*.$TYPE" | sort | head --lines=1`
		if [ $OLDFILE = "" ]
		then
			echo -e "\033[1;31mAll files from Audiologger deleted - exiting...\033[0m"
			exit 1;
		fi
	done;
}

# determine the language settings...
[ -f /etc/sysconfig/i18n ] && . /etc/sysconfig/i18n
case "$LANGUAGE" in
de|at|ch)
TI=" Audiologger "
BT="Audiologger"
M01="Dies ist ein einfaches Script um im MP3 oder im OGG  Format auf die Festplatte aufzunehmen. Es nimmt immer einfach eine Stunde auf, und speichert die Daten dann auf der Festplatte. Per Netzwerk kann man auf die Files zugreifen, oder sie auch einfach auf CD brennen. Abbrechen des Programms mit [Ctrl-C]"
M02="Bitte Qualität angeben"
B16="16Kbit - Radio, Sprache - sehr schlecht"
B24="24Kbit - Radio, Sprache - schlecht"
B32="32Kbit - Radio, Sprache"
B48="48Kbit - Radio, Sprache"
B56="56Kbit - Radio, bedingt Musik"
B64="64kbit - Radio, Musik"
B96="96kbit - gute Qualität"
B128="128kbit - CD-Qualität"
M03="Bitte Dateiformat wählen!"
M04="Ogg/Vorbis"
M05="MP3"
M06="Bitte Modus angeben"
M07="Mono"
M08="Joint-Stereo"
M09="Stereo"
M10="Wohin sollen denn die Daten gespeichert werden?"
M11="/ramdisk"
M12="Wieviel Platz soll auf der Platte an Speicherplatz freibleiben? Wenn weniger als dieser Platz auf der Platte frei ist, werden die ältesten Dateien vom Audiologger einfach gelöscht. Angabe in Megabyte:"
M13="10"
M14=" Samba starten? "
M15="Sollen wir den Samba-Server starten? - Damit sind die Dateien einfach im Netzwerk verfügbar. Der Rechner hat dann eine Freigabe die Audiologger heisst, allerdings read-only ist.\nDie resultierende Freigabe ist dann unter\n\n\\\\$myip\\$GENNAME \n\n zu erreichen"
M16=" NTP Date "
M17="Soll die Uhrzeit des Rechners mit der Internetzeit synchronisiert werden?"
M18="\033[1;33mAbbrechen mit mehrfachem Drücken von [Control-C]\033[0m\n\033[1;33moder nach der nächsten Aufnahme beenden mit 'q'\033[1;30m"
P01="\Zb\Z1'Rawrec' scheint noch zu laufen - sollen wir $BT abbrechen [Ja], oder soll rawrec getötet werden [Nein]"
MSTART="\033[1;35m== START =========================================>\033[0m"
;;
*)
TI=" Audiologger "
BT="Audiologger"
M01="This is a simple script to record in the MP3 or OGG format directly to the harddrive. It records for an hour and allows to fetch the files over the network. End the programm with [Ctrl-C]."
M02="Please choose bitrate"
B16="16Kbit - radio, voice - very bad"
B24="24Kbit - radio, voice - bad"
B32="32Kbit - radio, voice"
B48="48Kbit - radio, voice"
B56="56Kbit - radio, music"
B64="64kbit - radio, music"
B96="96kbit - fair quality"
B128="128kbit - CD-quality"
M03="Please choose fileformat"
M04="Ogg/Vorbis"
M05="MP3"
M06="Please choose mode"
M07="Mono"
M08="Joint-Stereo"
M09="Stereo"
M10="Where should the date be saved?"
M11="/ramdisk"
M12="How many space should remain on the harddisk. If there is less space than this on the disk the oldes files will just be deleted. Please choose number in megabyte:"
M13="10"
M14=" start samba ? "
M15="Should we start the samba server? - Then the files are available on the network on this computer by a network share called Audiologger, which is readonly\nThe resulting network-share can be reached on\\\\$myip\\$GENNAME \n"
M16=" NTP Date "
M17="Should we use timesynchronsation over the internet?"
M18="\033[1;33m stop by frequent pressing of [Control-C]\033[0m\n\033[1;33m or after the next recorning with 'q'\033[1;30m"
P01="\Zb\Z1'Rawrec' seems to run in background - should we stop $BT [Yes], or should rawrec be killed [No]"
MSTART="\033[1;35m== START =========================================>\033[0m"
;;
esac
##############
# print start dialog
$DIALOG --title "$TI" --backtitle "$BT" --cr-wrap --clear --msgbox "$M01" 0 0
##############
# get bitrate
tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/test$$
trap "rm -f $tempfile" 0 1 2 5 15
$DIALOG --backtitle "$BT" --nocancel --radiolist "$M02" 0 0 0 \
16 "$B16" off \
24 "$B24" off \
32 "$B32" off \
48 "$B48" off \
56 "$B56" off \
64 "$B64" on \
96 "$B96" off \
128 "$B128" off 2> $tempfile
BITRATE=`cat $tempfile`
##############
# get type
tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/test$$
trap "rm -f $tempfile" 0 1 2 5 15
$DIALOG --backtitle "$BT" --nocancel --radiolist "$M03" 0 0 2 ogg "$M04" on mp3 "$M05" off 2> $tempfile
TYPE=`cat $tempfile`
##############
# get mode
tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/test$$
trap "rm -f $tempfile" 0 1 2 5 15
$DIALOG --backtitle "$BT" --nocancel --radiolist "$M06" 0 0 3 m "$M07" off j "$M08" on s "$M09" off 2> $tempfile
MODE=`cat $tempfile`
##############
# get path 
tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/test$$
CONFIGS=`cut -d " " -f 2 /etc/fstab|grep /mnt | grep -v auto | grep -v ntfs|  sed s/$/\ off/g | awk {'print $1" "$1" "$2;'}`
trap "rm -f $tempfile" 0 1 2 5 15
$DIALOG --backtitle "$BT" --nocancel --radiolist "$M10" 0 0 0 $M11 "$M11" on $CONFIGS 2> $tempfile
PFAD=`cat $tempfile`
##############
# be sure and mount the path
if ! (mount | grep $PFAD > /dev/null) 
then mount -w $PFAD
fi
if ! (mount | grep $PFAD | grep \(rw > /dev/null)
then
mount -o remount -w $PFAD
fi
##############
# how many space should be left on the device?
tempfile=`tempfile 2>/dev/null` || tempfile=/tmp/test$$
trap "rm -f $tempfile" 0 1 2 5 15
$DIALOG --backtitle "$BT" --nocancel --inputbox "$M12" 0 0 "$M13" 2> $tempfile
MINLEFT=`cat $tempfile`
##############
# Check left space....
SPACELEFT=`df -m | grep $PFAD | awk {'print $4;'}`
case "$LANGUAGE" in
de|at|ch)
P02="Es ist weniger Platz auf der Platte ($SPACELEFT M), als Mindestplatz ($MINLEFT M) angefordert wurde\n Ich beende das Programm!"
;;
*)
P02="There is less space on the disk ($SPACELEFT M), than requested ($MINLEFT M) \n exiting..."
;;
esac
if [ $SPACELEFT -lt $MINLEFT ]
then
	$DIALOG --title "$TI" --backtitle "$BT" --cr-wrap --clear --msgbox "$P02" 0 0
	exit 1;
fi
###############
# Start Samba
value=1
        $DIALOG --backtitle "$BT" --title "$M14" --clear --yesno "$M15" 0 0
        value=$?
        if [ $value == 0 ]
        then
	/etc/init.d/samba stop
	SMBCONF=/etc/samba/smb.conf
	rm -f $SMBCONF
	sed "s/read only = yes/read only = no/" /KNOPPIX$SMBCONF >$SMBCONF
	sed "s/security = user/security = share/" /KNOPPIX$SMBCONF >$SMBCONF
	test -x $PFAD/$GENNAME || mkdirhier $PFAD/$GENNAME
	cat >>$SMBCONF <<EOF
[Audiologger]
	comment = Audiologger MP3/OGG-Archiv
	browseable = yes
	path = $PFAD/$GENNAME
	writeable = no
	guest ok = Yes
EOF
	/etc/init.d/samba start
	fi
###############
# Do timesynchronisation...
value=1
        $DIALOG --backtitle "$BT" --title "$M16" --clear --yesno "$M17" 0 0
        value=$?
        if [ $value == 0 ]
        then            
	[ -x /etc/init.d/ntpdate ] && /etc/init.d/ntpdate restart
        fi
###############
# Wieviele Sekunden sind es bis zur naechsten Stunde?
MINUTE=`date +%M`
SEC=`date +%S`
NEXTHOUR=`expr 60 \* \( 59 - $MINUTE \) + \( 60 - $SEC \)`
####################
# is rawrec still running?!
if (ps ax | grep rawrec | grep -v grep)
then
        $DIALOG --colors --title "$TI" --backtitle "$BT" --cr-wrap --clear --yesno "$P01" 0 0
        if [ $? == 0 ]
        then
                exit 1
        else
                killall -9 rawrec
                sleep 1
        fi
fi
###############
# Clear screen
clear;
###############
# record up to the next hour
careforspace
echo -e $MSTART
audiorecord $NEXTHOUR;
careforspace
###############
# after this, just record further and further
while [ "X$inp" != Xq ]; do
 read inp;
 echo -e $MSTART
 audiorecord $CHUNK;
 careforspace
done;

stty sane ## nicht vergessen!!
# end
