#!/bin/bash
export TEXTDOMAIN=pmusic

#default radio station
if [ "`grep "$(cut -d'|' -f2 $HOME/.pmusic/nowplaying)" "$STORAGE_DIR"/index_radio`" ]; then
	cut -d'|' -f1 $HOME/.pmusic/nowplaying > $WORKDIR/RADIOHITS_NAME
	cut -d'|' -f2 $HOME/.pmusic/nowplaying > $WORKDIR/RADIOHITS_URL
else
	mkdir "$STORAGE_DIR/radio-hits preset"
	echo 'RadioCrazy' > $WORKDIR/RADIOHITS_NAME
	echo 'http://www.swissradio.ch/streams/6034.m3u' > $WORKDIR/RADIOHITS_URL
fi
echo '' > $WORKDIR/RADIOHITS_PATH
echo '' > $WORKDIR/RADIOHITS_OPTIONS
echo true > $WORKDIR/radiohits_CHK_MIN_SIZE

RADIOHITS_NAME="$(<$WORKDIR/RADIOHITS_NAME)"

update_index (){
	echo "$(gettext 'Updating database')" > $WORKDIR/splashtext
	$APPDIR/box_splash &
	#include radio-hits in MyMusic index
	find "$STORAGE_DIR/radio-hits preset/" -exec cut -d'|' -f2 {} \; | sort -u > $WORKDIR/tmp_radiohits
	while read I; do
		rm -fr "$I/incomplete"
		$APPDIR/func_index -quick_update "$I"
	done < $WORKDIR/tmp_radiohits
	echo 100 > $WORKDIR/splash
}
export -f update_index

grab (){
	find "$STORAGE_DIR/radio-hits preset/" -exec cut -d'|' -f2 {} \; | sort -u > $WORKDIR/tmp_radiohits
	if [!  -s $WORKDIR/tmp_radiohits ]; then
		TXT1="<b>$(gettext 'No preset is defined')</b>"
		. $APPDIR/box_ok
		exit
	fi
	#kill process
	TMP="`ps -eo pid,command`"
	while read RADIOHITS_PATH; do
		for I in `echo "$TMP" | grep -F "$RADIOHITS_PATH" | grep -F streamripper | awk '{print $1}'`; do kill -9 $I 2> /dev/null; done
	done < $WORKDIR/tmp_radiohits
	#---
	while read RADIOHITS_NAME; do
		RADIOHITS_PATH="`cut -d'|' -f2 "$STORAGE_DIR/radio-hits preset/$RADIOHITS_NAME"`"
		RADIOHITS_URL="`cut -d'|' -f3 "$STORAGE_DIR/radio-hits preset/$RADIOHITS_NAME"`"
		RADIOHITS_OPTIONS="`cut -d'|' -f4 "$STORAGE_DIR/radio-hits preset/$RADIOHITS_NAME"`"
		echo "connecting... $RADIOHITS_URL" > "$WORKDIR/output_streamripper$RADIOHITS_NAME"
		streamripper "$RADIOHITS_URL" -d "$RADIOHITS_PATH" -s -o never -k 1 --with-id3v1 -u WinampMPEG/5.0 ${RADIOHITS_OPTIONS} > "$WORKDIR/output_streamripper$RADIOHITS_NAME" 2>&1 &
	done < $WORKDIR/radiohits_presets
}

save_preset (){
	#check if all info is on place
	if [ ! "$RADIOHITS_NAME" ] || [ ! "$RADIOHITS_URL" ] || [ ! "$RADIOHITS_PATH" ]; then
		TXT1="$(gettext 'Missing info. Name, URL and download directory must all be defined before saving')"
		. $APPDIR/box_ok
		exit
	fi
	#missing download path
	if [ ! -d "$RADIOHITS_PATH" ]; then
		TXT1="$(gettext 'Download directory is missing. Do you want to create it?')"
		. $APPDIR/box_yesno
		[ $EXIT != "yes" ] && exit
		mkdir -p "$RADIOHITS_PATH"
	fi
	#check if exist
	if [ -f "$STORAGE_DIR/radio-hits preset/$RADIOHITS_NAME" ]; then
		TXT1="<b>${RADIOHITS_NAME}</b> $(gettext 'already exists')"; TXT2="$(gettext 'Do you want to overwrite existing file?')"
		. $APPDIR/box_yesno
		[ $EXIT != "yes" ] && exit
	fi
	#save
	echo "$RADIOHITS_NAME|$RADIOHITS_PATH|$RADIOHITS_URL|$RADIOHITS_OPTIONS" > "$STORAGE_DIR/radio-hits preset/$RADIOHITS_NAME"
	#add to favorites
	if [ ! "`grep -F "${RADIOHITS_PATH}|" "$STORAGE_DIR/favorites"`" ]; then
		[ -d "$RADIOHITS_PATH" ] && echo "$RADIOHITS_PATH|$(basename "$RADIOHITS_PATH")||||||||||||$RADIOHITS_PATH|gtk-directory" >> "$STORAGE_DIR/favorites"
	fi
	#update list
	ls -1 "$STORAGE_DIR/radio-hits preset" | sort > $WORKDIR/radiohits_presets
	cp $WORKDIR/radiohits_presets $WORKDIR/radiohits_output
	rm $WORKDIR/xml_pmusic #make sure gui updates at next run to show this new menuitem
}

fetch_playing (){
	cp -f $WORKDIR/PLAYLIST $WORKDIR/RADIOHITS_URL
	echo '' > $WORKDIR/RADIOHITS_NAME
	echo '' > $WORKDIR/RADIOHITS_PATH
	echo '' > $WORKDIR/RADIOHITS_OPTIONS
}

output (){
	echo -n > $WORKDIR/radiohits_output
	while read RADIOHITS_NAME; do
		echo -n "${RADIOHITS_NAME}|" >> $WORKDIR/radiohits_output
		tail -c 1000 "$WORKDIR/output_streamripper$RADIOHITS_NAME" | tr "\r" "\n" | tail -n1 >> $WORKDIR/radiohits_output
	done < $WORKDIR/radiohits_presets
}

build_info_radiohits (){
	gettext 'RadioHits Grabber is a tool to split up radio-streams to music tracks - based on meta-information. This means you will get one mp3/ogg file, with correct naming, for each of the songs the radio station plays.' > $WORKDIR/box_ok_txt1
	echo -en "\n\n<span fgcolor='"'darkgreen'"'><b><big>*</big></b></span> " >> $WORKDIR/box_ok_txt1
	gettext 'Grab a top-40 station over-night once a week, and you will always have the latest hits available. Or choose a radio station playing your preferred genre and let it grab a week or so. - You will then have the most popular songs on your harddrive.' >> $WORKDIR/box_ok_txt1
	echo -en "\n\n<span fgcolor='"'darkgreen'"'><b><big>*</big></b></span> " >> $WORKDIR/box_ok_txt1
	gettext 'Be aware that this will require a lot of free space on your harddisk.' >> $WORKDIR/box_ok_txt1
	echo -en "\n\n<span fgcolor='"'darkgreen'"'><b><big>*</big></b></span> " >> $WORKDIR/box_ok_txt1
	gettext 'Correct splitting and naming depends on the meta-information. Not all radio-stations provide useful meta-info. You might need to test some of your favorite stations to build a local hit-db without too much manual work. Both 1.FM and 181.fm (USA) provides a variety of good-quality-channels for many genres.' >> $WORKDIR/box_ok_txt1
	echo -en "\n\n<span fgcolor='"'darkgreen'"'><b><big>*</big></b></span> " >> $WORKDIR/box_ok_txt1
	gettext 'If a track starts badly or contains a piece of commercials, you can just delete the file and wait for next play. Or, you can edit the track manually in programs like MhWaveEdit or Audacity... The fader effect is very useful to fade in/out the song.' >> $WORKDIR/box_ok_txt1
}

export -f grab save_preset fetch_playing output delete_preset build_info_radiohits

find "$STORAGE_DIR/radio-hits preset/" -type f -printf "%f\n" | sort > $WORKDIR/radiohits_presets
cp $WORKDIR/radiohits_presets $WORKDIR/radiohits_output #for <tree>
$APPDIR/func_svg -heading "$(gettext 'Radio Hits')" > /dev/null #we don't use the standard xml code here

S='
<window title="pMusic - '$(gettext 'Radio Hits')'" icon-name="pmusic" default_height="550">
<vbox>
 <vbox space-expand="false" space-fill="false">
  <hbox spacing="0" height="80" scrollable="true" space-expand="true" space-fill="true" vscrollbar-policy="2" hscrollbar-policy="2">
   <eventbox name="svgheading">
    <hbox space-expand="true" space-fill="true">
     <text width-request="20" space-expand="false" space-fill="false"><label>""</label></text>
     <text ypad="40" use-markup="true" space-expand="false" space-fill="false"><label>"<i>'$(gettext 'Split up radio-streams to mp3/ogg files...
...with correct naming.')'</i>"</label></text>
     <text space-expand="true" space-fill="true"><label>""</label></text>
     <vbox space-expand="false" space-fill="false">
      <text height-request="2" space-expand="false" space-fill="false"><label>""</label></text>
      <button can-focus="false" image-position="2" space-expand="false" space-fill="false">
       <label>" '$(gettext 'Info')' "</label>
       <input file stock="gtk-info"></input>
       <action>build_info_radiohits; IMG=info; FRAME='$(gettext 'Info')'; HEADING="'$(gettext 'Radio Hits')'"; . '$APPDIR'/box_ok -txt1_file &</action>
      </button>
      <text space-expand="true" space-fill="true"><label>""</label></text>
     </vbox>
     <text height-request="2" space-expand="false" space-fill="false"><label>""</label></text>
    </hbox>
   </eventbox>
  </hbox>
 <frame '$(gettext 'Preset')'>
  <hbox>
   <text use-markup="true" width-request="120" space-expand="false" space-fill="false"><label>"<b>'$(gettext 'Name')'</b>"</label></text>
   <entry space-expand="true" space-fill="true">
    <variable>RADIOHITS_NAME</variable>
    <default>"'$RADIOHITS_NAME'"</default>
    <input file>'$WORKDIR'/RADIOHITS_NAME</input>
   </entry>
   <text width-request="30"><label>""</label></text>
  </hbox>
  <hbox>
   <text use-markup="true" width-request="120"><label>"<b>URL</b>"</label></text>
   <entry><variable>RADIOHITS_URL</variable><input file>'$WORKDIR'/RADIOHITS_URL</input></entry>
   <button tooltip-text="'$(gettext 'Fetch playing stream')'">
    <input file stock="gtk-go-back"></input>
    <action>fetch_playing</action>
    <action>refresh:RADIOHITS_URL</action>
    <action>refresh:RADIOHITS_NAME</action>
    <action>refresh:RADIOHITS_PATH</action>
    <action>refresh:RADIOHITS_OPTIONS</action>
   </button>
  </hbox>
  <hbox>
   <text use-markup="true" width-request="120"><label>"<b>'$(gettext 'Download to')'</b>"</label></text>
   <entry accept="directory"><variable>RADIOHITS_PATH</variable><input file>'$WORKDIR'/RADIOHITS_PATH</input></entry>
   <button><input file stock="gtk-open"></input><action type="fileselect">RADIOHITS_PATH</action></button>
  </hbox>
  <expander>
   <vbox space-expand="false" space-fill="false">
    <hbox tooltip-text="'$(gettext 'Here you can define advanced options to the executing streamripper command')'">
     <text use-markup="true" width-request="120" space-expand="false" space-fill="false"><label>"<b>'$(gettext 'Extra options')'</b>"</label></text>
     <entry space-expand="true" space-fill="true"><variable>RADIOHITS_OPTIONS</variable><input file>'$WORKDIR'/RADIOHITS_OPTIONS</input></entry>
     <button tooltip-text="'$(gettext 'Show available Streamripper options in texteditor')'" space-expand="false" space-fill="false"><input file stock="gtk-info"></input><action>streamripper -h > '$WORKDIR'/radiohits_tmp; '$TEXT_EDITOR' '$WORKDIR'/radiohits_tmp</action></button>
    </hbox>
    <hbox>
     <text use-markup="true" width-request="120" space-expand="false" space-fill="false"><label>"<b>'$(gettext 'Command')'</b>"</label></text>
     <statusbar has-resize-grip="false" space-expand="true" space-fill="true">
      <variable>RADIOHITS_COMMAND</variable>
      <default>""</default>
      <input>echo "streamripper \"$RADIOHITS_URL\" -d \"$RADIOHITS_PATH\" -s -o never -k 1 --with-id3v1 -u WinampMPEG/5.0 $RADIOHITS_OPTIONS"</input> 
     </statusbar>
     <button space-expand="false" space-fill="false"><input file stock="gtk-refresh"></input><action>refresh:RADIOHITS_COMMAND</action></button>
    </hbox>
   </vbox>
   <label>'$(gettext 'Advanced')'</label>
  </expander>
  <hbox>
   <button tooltip-text="'$(gettext 'Save preset to add it to the grabbing list.')'">
    <input file stock="gtk-save"></input>
    <label>"'$(gettext 'Save preset')'"</label>
    <action>save_preset</action>
    <action>refresh:OUTPUT</action>
   </button>
  </hbox>
 </frame>
</vbox>
<vbox space-expand="true" space-fill="true">
 <timer visible="false" space-expand="false" space-fill="false">
  <variable>TIMER</variable>
  <sensitive>false</sensitive>
  <action>output</action>
  <action>refresh:OUTPUT</action>
 </timer>
 <vbox space-expand="true" space-fill="true">
  <tree stock-id="gtk-audio_url" headers-visible="false" hover-selection="true" space-expand="true" space-fill="true">
   <variable>OUTPUT</variable>
   <label>a|b</label>
   <input file>'$WORKDIR'/radiohits_output</input>
   <action signal="button-press-event">if [ $PTR_BTN -eq 3 ]; then echo "$OUTPUT" > '$WORKDIR'/RADIOHITS_PRESS_EVENT; . '$APPDIR'/menu_radiohits; fi</action>
   <action signal="button-press-event">refresh:OUTPUT</action>
   <action signal="button-release-event">cut -d"|" -f1 "'$STORAGE_DIR'/radio-hits preset/$OUTPUT" > '$WORKDIR'/RADIOHITS_NAME</action>
   <action signal="button-release-event">cut -d"|" -f2 "'$STORAGE_DIR'/radio-hits preset/$OUTPUT" > '$WORKDIR'/RADIOHITS_PATH</action>
   <action signal="button-release-event">cut -d"|" -f3 "'$STORAGE_DIR'/radio-hits preset/$OUTPUT" > '$WORKDIR'/RADIOHITS_URL</action>
   <action signal="button-release-event">cut -d"|" -f4 "'$STORAGE_DIR'/radio-hits preset/$OUTPUT" > '$WORKDIR'/RADIOHITS_OPTIONS</action>
   <action signal="button-release-event">refresh:RADIOHITS_NAME</action>
   <action signal="button-release-event">refresh:RADIOHITS_URL</action>
   <action signal="button-release-event">refresh:RADIOHITS_PATH</action>
   <action signal="button-release-event">refresh:RADIOHITS_OPTIONS</action>
  </tree>
  <hbox space-expand="false" space-fill="false">
   <vbox space-expand="false" space-fill="false">
    <checkbox space-expand="false" space-fill="false">
     <variable>CHK_MIN_SIZE</variable>
     <default>true</default>
     <label>'$(gettext 'Delete tracks smaller than 1Mb (adverts?)')'</label>
     <action>echo $CHK_MIN_SIZE > '$WORKDIR'/radiohits_CHK_MIN_SIZE</action>
    </checkbox>
    <hbox space-expand="false" space-fill="false">
     <button space-expand="false" space-fill="false">
      <input file stock="gtk-quit"></input>
      <label>'$(gettext 'Quit and Update db')'</label>
      <action>update_index</action>
      <action>exit:EXIT</action>
     </button>
     <button tooltip-text="'$(gettext 'Add new tracks to database, and make them searchable')'" space-expand="false" space-fill="false">
      <input file stock="gtk-apply"></input>
      <label>'$(gettext 'Update db')'</label>
      <action>update_index</action>
     </button>
     <text space-expand="true" space-fill="true"><label>""</label></text>
    </hbox>
   </vbox>
   <text space-expand="true" space-fill="true"><label>""</label></text>
   <button space-expand="false" space-fill="false" image-position="2">
    <input file stock="gtk-execute"></input>
    <label>"'$(gettext 'Start grabbing tracks')'"</label>
    <action>enable:TIMER</action>
    <action>grab &</action>
   </button>
  </hbox>
 </vbox>
</vbox>
</vbox>
</window>'
[ $TOOLTIPS = false ] && S="`echo "$S" | sed 's%tooltip-text%tooltipXXXtext%g'`" #deactivate tooltips
. $APPDIR/func -reset_gtk
export pmusic_radiohits="`echo "$S" | sed 's/##.*//'`" #I use double hash (##) for comments. --> as #FF0000
I=$IFS; IFS=""
for STATEMENTS in $($GTKDIALOG -p pmusic_radiohits); do
	eval $STATEMENTS
done
IFS=$I


find "$STORAGE_DIR/radio-hits preset/" -exec cut -d'|' -f2 {} \; | sort -u > $WORKDIR/tmp_radiohits
#kill process
TMP="`ps -eo pid,command`"
while read RADIOHITS_PATH; do
	for I in `echo "$TMP" | grep -F "$RADIOHITS_PATH" | grep -F streamripper | awk '{print $1}'`; do kill -9 $I 2> /dev/null; done
done < $WORKDIR/tmp_radiohits
#cleanup
while read RADIOHITS_PATH; do
	rm -f $WORKDIR/output_streamripper*
	[ "`cat $WORKDIR/radiohits_CHK_MIN_SIZE`" = true ] && find "$RADIOHITS_PATH" -maxdepth 1 -mindepth 1 -type f -size 1M -iname "*.mp3" -exec rm {} \;
	[ "`cat $WORKDIR/radiohits_CHK_MIN_SIZE`" = true ] && find "$RADIOHITS_PATH" -maxdepth 1 -mindepth 1 -type f -size 1M -iname "*.ogg" -exec rm {} \;
done < $WORKDIR/tmp_radiohits

