#!/bin/bash
#
# Copyright (c) 2013 Dejan Rackovic <dejan@b0x.me>
# 
# 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, or
# (at your option) any later version.
#
# 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/>.

#Export variables

export TEXTDOMAIN=simplegtkradio
export OUTPUT_CHARSET=UTF-8

#export SGRDIR=$(cd `dirname "$0"` && pwd)
export SGRNAME=$(basename "$0")
#export SGRBIN="$SGRDIR/$SGRNAME"
export SGRBIN=$(realpath "$0")
export SGRDIR=$(dirname "$SGRBIN")
export SGRTMP="/tmp/sgr.$USER"
export SGRCONF="$HOME/.config/simplegtkradio"
export sgrVERSION="0.1.18"

#Check files
[ ! -d $SGRCONF/playlists ] && mkdir -p $SGRCONF/playlists
[ ! -f $SGRCONF/options ] && cp $SGRDIR/options $SGRCONF/options
if [ ! -f $SGRCONF/playlists/default ];then 
	cp $SGRDIR/playlists/playlist.* $SGRCONF/playlists/
	ln -s $SGRCONF/playlists/playlist.default $SGRCONF/playlists/default
fi
#End check files

#Load config
. $SGRCONF/options

##RUN##
case $1 in

stop)
MRUN=`pidof mpv`
if [ "$MRUN" != "" ]; then 
SGRNOTIFYPID=$(ps | grep "$SGRNAME notify" | grep -v grep |  awk '{print $1}')
[ "$SGRNOTIFYPID" != "" ] && kill -s KILL $SGRNOTIFYPID
killall mpv;
rm -f $SGRTMP/mpv-output
#rm -f $SGRTMP/url
#echo "$(gettext 'None')" > $SGRTMP/station
echo "$(gettext 'Radio stopped')" > $SGRTMP/NP
echo "false" > $SGRTMP/timer
fi
;;

-u)
	[ "$2" = "" ] && exit
	$SGRBIN stop
	STREAMURL="$2"
	[ "$3" = "-s" ] && [ "$4" != "" ] && STATION="$4"
	[ "$STATION" = "" ] && STATION="$STREAMURL"
	echo "$(gettext 'Playing') $STATION" > $SGRTMP/NP 
	echo "$STATION" > $SGRTMP/station
	echo "$STREAMURL" > $SGRTMP/url
	OPTS="-msglevel all=-1:demuxer=5"
	case $STREAMURL in
	*.pls|*.m3u|*.asx|*.ram|http://yp.shoutcast.com/sbin/tunein-station.pls?id=*)
	OPTS="$OPTS -playlist"
	;;
	esac
	mpv $STREAMURL > $SGRTMP/mpv-output &
	[ "$STBENABLED" = "true" ] && echo "true" > $SGRTMP/timer
	$SGRBIN notify &
;;

parse_spiff)
	if [ -f "$2" ];then 
XSPFFILE="$2"
else
wget $2 -O $SGRTMP/playlist.xspf
XSPFFILE=$SGRTMP/playlist.xspf
fi
STATION=$(cat "$XSPFFILE" | grep '<title>' | sed 's#.*<title>##' |sed 's#</title>.*##')
CNTLOCS=$(cat "$XSPFFILE" | grep '<location>' | wc -l)
if [ "$CNTLOCS" -gt "1" ];then
	if [ "$PLAYFIRST" = "true" ];then
	STREAMURL=$(cat "$XSPFFILE" | grep '<location>' | head -n 1 | sed 's#.*<location>##' | sed 's#</location>.*##')
	else
STATIONINFO=$(cat "$XSPFFILE" | grep '<info>' | sed 's#.*<info>##' |sed 's#</info>.*##')
[ "$STATIONINFO" = "" ] && STATIONINFO="$(gettext 'No additional info')"
cat "$XSPFFILE" | grep '<location>' > $SGRTMP/playlist.xspf.locations
CITEMS=""
while read line
do
LOC=$(echo "$line" | sed 's#.*<location>##' | sed 's#</location>.*##')
CITEMS="$CITEMS <item>$LOC</item>"
done <$SGRTMP/playlist.xspf.locations

export SEL_LOC='<window title="'$(gettext 'Choose stream url')'" width-request="450" image-name="'"$SGRDIR"'/data/radiotray.png"><vbox>
 <text><label>""</label></text>
<text><label>'"$STATION"'</label></text>
<text><label>'"$STATIONINFO"'</label></text>
<text><label>'"$CNTLOCS"' '$(gettext 'stream urls found in playlist')'</label></text>
<text><label>'$(gettext 'Choose which one to play:')'</label></text>
 <text><label>""</label></text>
<combobox>
<variable>STREAMURL</variable>
'"$CITEMS"'
</combobox>
<button ok></button>
</vbox>
</window>
'
I=$IFS; IFS=""
for STATEMENTS in  $(gtkdialog4 --program=SEL_LOC --center); do
   eval $STATEMENTS
done
IFS=$I 
fi
else
STREAMURL=$(cat "$XSPFFILE" | grep '<location>' | sed 's#.*<location>##' | sed 's#</location>.*##')
fi
[ "$STREAMURL" = "" ] && exit
[ "$STATION" = "" ] && STATION="$STREAMURL"
$SGRBIN -u "$STREAMURL" -s "$STATION" &
;;

url)
if [ "$2" != "" ];then
STREAMURL="$2"
else
export SGR_url='
<window title="'$(gettext 'Radio URL')'" default_width="300" image-name="'"$SGRDIR"'/data/radiotray.png">
<vbox>
<text><label>'$(gettext 'Enter stream URL:')'</label></text>
<entry><variable>STREAMURL</variable></entry>
<hbox><button ok></button><button cancel></button></hbox>
</vbox>
</window>
'

I=$IFS; IFS=""
for STATEMENTS in  $(gtkdialog4 --program=SGR_url --center); do
   eval $STATEMENTS
done
IFS=$I 
fi

if [ "$STREAMURL" != "" ];then
	case $STREAMURL in
	*.xspf)
	$SGRBIN parse_spiff "$STREAMURL"
	;;
	*)
	$SGRBIN -u "$STREAMURL"
	;;
	esac
fi
;;

-p)
	[ "$2" = "" ] && exit
	STREAMURL="$2"
	STATION=$(grep -m 1 "$STREAMURL" $SGRTMP/window | cut -d "|" -f 2)
	$SGRBIN -u "$STREAMURL" -s "$STATION"
;;
	
play)
#Play radio
MRUN=`pidof mpv`
[ "$MRUN" != "" ] && exit
if [ -f "$SGRTMP/url" ];then
STREAMURL=$(cat "$SGRTMP/url")
[ -f "$SGRTMP/station" ] && STATION=$(cat "$SGRTMP/station")
[ "$STATION" = "" ] && STATION="$STREAMURL"
$SGRBIN -u "$STREAMURL" -s "$STATION" &
else
[ ! -f "$SGRTMP/num" ] && echo "1" > $SGRTMP/num
NUM=`cat $SGRTMP/num`
$SGRBIN $NUM &
fi
;;

next)
#Play next station
STCOUNT=$(sed = "$SGRCONF/playlists/default" | tail -n 2 | head -n 1)
[ ! -f "$SGRTMP/num" ] && echo "1" > $SGRTMP/num
NUM=$(cat "$SGRTMP/num")
NUM=$(($NUM+1))
[ "$NUM" -gt "$STCOUNT" ] && NUM="1"
$SGRBIN $NUM &
;;

prev)
#Play previous station
STCOUNT=$(sed = $SGRCONF/playlists/default | tail -n 2 | head -n 1)
[ ! -f "$SGRTMP/num" ] && echo "1" > $SGRTMP/num
NUM=`cat "$SGRTMP/num"`
NUM=$(($NUM-1))
[ "$NUM" -le "0" ] && NUM="$STCOUNT"
$SGRBIN $NUM &
;;

last-five)
#Show last five songs
export SGR_last='
<window title="'$(gettext 'Simple GTK Radio - last 5 played')'" resizable="false" decorated="false" image-name="'"$SGRDIR"'/data/radiotray.png">
<vbox border-width="10">
<text selectable="true" wrap="true" justify="2"><input>tail -n 5 $SGRTMP/radio-playlist</input></text>
<button label="'$(gettext 'Show playlist log')'"><action>$SGRBIN edit log &</action><action>exit:Quit</action></button>
   <button  has-focus="true"><label>OK</label>
      <input file stock="gtk-ok"></input><action>exit:Quit</action></button>
</vbox>
</window>
'
gtkdialog4 --program=SGR_last --center &
;;

edit)
[ "$2" = "log" ] && SGREDITFILE="$SGRTMP/radio-playlist" && SGREDITTITLE="Playlist log"
[ "$2" != "log" ] && SGREDITFILE="$SGRCONF/playlists/default" && SGREDITTITLE="Edit playlist"

if [ "$USEEDTR" = "true" ];then
$EDTR $SGREDITFILE &
else
export SGR_EDIT='<window title="'"$SGREDITTITLE"'" width-request="600" height-request="450"><vbox>
<edit>
<variable>PLSEDIT</variable>
<input file>'"$SGREDITFILE"'</input>
</edit>
<hbox>
<button><label>'$(gettext 'Save')'</label><input file stock="gtk-save"></input>
<action>echo -n "$PLSEDIT" > '"$SGREDITFILE"'</action>
<action>exit:Saved</action>
</button>
<button cancel></button></hbox>
</vbox></window>'

gtkdialog4 --program=SGR_EDIT --center
fi
;;

save)
[ ! -f $SGRTMP/url ] && exit
STREAMURL=$(cat $SGRTMP/url)
STATION=$(cat $SGRTMP/station)
PLITEMS=""
for i in $SGRCONF/playlists/playlist.*;do
PLNAME=`basename $i | sed 's/playlist.//'`
PLITEMS="$PLITEMS <item>$PLNAME</item>"
done

export SAVE_DIAL='<window title="'$(gettext 'Save stream')'" default_width="400" image-name="'"$SGRDIR"'/data/radiotray.png"><vbox>
<text><label>""</label></text>
<text><label>'$(gettext 'Stream name:')'</label></text>
<entry><variable>STATION</variable><default>'"$STATION"'</default></entry>
<text><label>""</label></text>
<text><label>'$(gettext 'Stream url:')'</label></text>
<entry><variable>STREAMURL</variable><default>'"$STREAMURL"'</default></entry>
<text><label>""</label></text>
<hbox>
<text><label>'$(gettext 'Add to playlist:')'</label></text>
<combobox>
<variable>PLIST</variable>
<default>default</default>
'"$PLITEMS"'
</combobox>
<button tooltip-text="'$(gettext 'Save')'"><input file stock="gtk-save"></input><action>exit:OK</action></button>
<button tooltip-text="'$(gettext 'Cancel')'"><input file stock="gtk-cancel"></input><action>exit:Cancel</action></button>
</hbox>
</vbox></window>'

I=$IFS; IFS=""
for STATEMENTS in  $(gtkdialog4 --program=SAVE_DIAL --center); do
   eval $STATEMENTS
done
IFS=$I

if [ "$EXIT" = "OK" ] && [ "$STREAMURL" != "" ] && [ "$STATION" != "" ] && [ "$PLIST" != "" ];then
PLIST=$(echo "$PLIST" | sed 's/ /_/g')
IHAVEIT=$(grep -h "$STREAMURL" $SGRCONF/playlists/playlist.$PLIST)
if [ "$IHAVEIT" = "" ];then
#check if file ends with newline
ENDNEW=$(sed = $SGRCONF/playlists/playlist.$PLIST | tail -n 2 | head -n 1)
ENDNEW2=$(wc -l <$SGRCONF/playlists/playlist.$PLIST)
[ "$ENDNEW" != "$ENDNEW2" ] && echo "" >> $SGRCONF/playlists/playlist.$PLIST
#end check newline, now add station:
echo "$STREAMURL|$STATION" >> $SGRCONF/playlists/playlist.$PLIST
else
OLDNAME=$(echo "$IHAVEIT" | cut -d "|" -f 2)
[ "$OLDNAME" = "$STATION" ] && exit
sed -i "s#|$OLDNAME#|$STATION#" $SGRCONF/playlists/playlist.$PLIST
echo "$STATION" > $SGRTMP/station
fi
fi

;;

[0-9]*)
STREAMURL=`sed -n $1p $SGRCONF/playlists/default`
STATION=$(echo $STREAMURL | cut -d "|" -f 2 )
STREAMURL=$(echo $STREAMURL | cut -d "|" -f 1 )
[ "$STREAMURL" = "Category" ] && exit
echo "$1" > $SGRTMP/num
$SGRBIN -u "$STREAMURL" -s "$STATION"
;;

*.pls|*.m3u|*.asx|*.ram|http://yp.shoutcast.com/sbin/tunein-station.pls?id=*)
STREAMURL="$1"
STATION="$1"
$SGRBIN -u "$STREAMURL" -s "$STATION"
;;

*.xspf)
$SGRBIN parse_spiff "$1"
;;

search)
[ ! "$2" ] && ln -sf $SGRCONF/playlists/default $SGRTMP/window  && exit
SEARCH="$2"
grep -ih "$SEARCH" $SGRCONF/playlists/playlist.* |  grep -v "Category" | sort -f -t '|' -k 2 -u > $SGRTMP/search
CNT=`wc -l <$SGRTMP/search`
if [ "$CNT" != "0" ];then
ln -sf $SGRTMP/search $SGRTMP/window
else
export GREP_RESULTS='<window title="'$(gettext 'Search results')'">
<vbox>
<text><label>""</label></text>
<text><label>'$(gettext 'No results found for:')' '"$SEARCH"'</label></text>
<text><label>""</label></text>
<button ok></button>
</vbox>
</window>'
gtkdialog4 --program=GREP_RESULTS --center
fi
;;

savesearch)
[ ! -f $SGRTMP/search ] && exit
[ "$2" = "" ] && exit
SRCHPLS=$(echo "$2" | sed 's/ /_/g')
if [ ! -f $SGRCONF/playlists/playlist.$SRCHPLS ];then
cp $SGRTMP/search $SGRCONF/playlists/playlist.$SRCHPLS

export SAVEDMSG='<window title="'$(gettext 'Search saved')'"  width-request="150" image-name="'"$SGRDIR"'/data/radiotray.png"><vbox>
<text wrap="true"><label>'$(gettext 'Saved')'</label></text>
<button ok></button>
</vbox></window>' 
gtkdialog4 --program=SAVEDMSG --center

fi
;;

rec)
RIPURL=$(cat "$SGRTMP/url")
[ "$RIPURL" = "" ] && exit
[ "$RIPDIR" = "" ] && RIPDIR="$HOME"
RIPPER=`which streamripper`
if [ -x "$RIPPER" ];then
[ "$SRIPOPTS" = "" ] && SRIPOPTS="-u mpv"
xterm -e streamripper $RIPURL $SRIPOPTS -d $RIPDIR
else
RIPNAME=sgr$(date +%H%M%S)
[ "$MRIPOPTS" = "" ] && MRIPOPTS="-dumpstream -dumpfile $RIPDIR/$RIPNAME"
case $RIPURL in
	*.pls|*.m3u|*.asx|*.ram|http://yp.shoutcast.com/sbin/tunein-station.pls?id=*)
	MRIPOPTS="$MRIPOPTS -playlist"
	;;
esac
xterm -e mpv $MRIPOPTS $RIPURL
fi
;;

prefs)
#Defaults, if not found in config file:
[ "$USEEDTR" = "" ] && USEEDTR="false"
[ "$EDTR" = "" ] && EDTR="geany"
[ "$HOWLONG" = "" ] && HOWLONG="30m"
[ "$PLAYFIRST" = "" ] && PLAYFIRST="true"
[ "$RIPDIR" = "" ] && RIPDIR="$HOME"
[ "$SRIPOPTS" = "" ] && SRIPOPTS="-u mpv"
[ "$STBENABLED" = "" ] && STBENABLED="true"
[ "$VLMENABLED" = "" ] && VLMENABLED="true"
[ "$STNENABLED" = "" ] && STNENABLED="true"
[ "$HSENABLED" = "" ] && HSENABLED="true"
[ "$NPENABLED" = "" ] && NPENABLED="true"
[ "$SGRDECOR" = "" ] && SGRDECOR="true"
[ "$SKIPTASKBAR" = "" ] && SKIPTASKBAR="false"
[ "$VLMCH" = "" ] && VLMCH="Master"

VLMCHITEMS="<item>Master</item>"
for i in PCM Speaker Headphone;do 
HASCH=$(amixer scontrols | grep "$i" | grep -v grep)
[ "$HASCH" != "" ] && VLMCHITEMS="$VLMCHITEMS <item>$i</item>"
done
EDTRITEMS="<item>geany</item>"
for i in leafpad nicoedit;do 
HASEDTR=$(which "$i")
[ "$HASEDTR" != "" ] && EDTRITEMS="$EDTRITEMS <item>$i</item>"
done
export PREFS_DIAG='<window title="'$(gettext 'Preferences')'" image-name="'"$SGRDIR"'/data/radiotray.png"><vbox>
<notebook labels="'$(gettext 'General|Toolbars|About')'">
<frame>
<text><label>""</label></text>
<hbox><checkbox tooltip-text="'$(gettext 'For editing playlist and viewing logs')'"><label>'$(gettext 'Use external editor')'</label>
<variable>USEEDTR</variable><default>'"$USEEDTR"'</default>
<action>if true enable:EDTR</action>
<action>if false disable:EDTR</action>
</checkbox>
<comboboxentry sensitive="'"$USEEDTR"'">
<variable>EDTR</variable>
<default>'"$EDTR"'</default>
'"$EDTRITEMS"'
</comboboxentry></hbox>
<hbox>
<text><label>'$(gettext 'Interval for station changer:')'</label></text>
<entry><variable>HOWLONG</variable><default>'"$HOWLONG"'</default></entry></hbox>
<text><label>'$(gettext 'Directory for recorded content:')'</label></text>
<hbox><entry fs-action="folder" fs-folder="'"$RIPDIR"'"><variable>RIPDIR</variable><default>'"$RIPDIR"'</default></entry><button><action type="fileselect">RIPDIR</action><input file stock="gtk-open"></input></button></hbox>
<text><label>'$(gettext 'Additional parameters for streamripper')'</label></text>
<entry><variable>SRIPOPTS</variable><default>'"$SRIPOPTS"'</default></entry>
<hbox><text><label>'$(gettext 'Volume bar controls channel:')'</label></text>
<comboboxentry>
<variable>VLMCH</variable>
<default>'"$VLMCH"'</default>
'"$VLMCHITEMS"'
</comboboxentry></hbox>
<checkbox><label>'$(gettext 'Play first url in .xspf playlist')'</label>
<variable>PLAYFIRST</variable><default>'"$PLAYFIRST"'</default></checkbox>
</frame>
<frame>
<text><label>""</label></text>
<text><label>Select visible toolbars:</label></text>
<text><label>""</label></text>
<checkbox><label>'$(gettext 'Station name')'</label>
<variable>STNENABLED</variable><default>'"$STNENABLED"'</default></checkbox>
<checkbox><label>'$(gettext 'Now playing')'</label>
<variable>NPENABLED</variable><default>'"$NPENABLED"'</default></checkbox>
<checkbox><label>'$(gettext 'Separator')'</label>
<variable>HSENABLED</variable><default>'"$HSENABLED"'</default></checkbox>
<checkbox><label>'$(gettext 'Volume')'</label>
<variable>VLMENABLED</variable><default>'"$VLMENABLED"'</default></checkbox>
<checkbox><label>'$(gettext 'Elapsed time')'</label>
<variable>STBENABLED</variable><default>'"$STBENABLED"'</default></checkbox>
<text><label>""</label></text>
<checkbox><label>'$(gettext 'Use window manager decorations')'</label>
<variable>SGRDECOR</variable><default>'"$SGRDECOR"'</default></checkbox>
<checkbox><label>'$(gettext 'Do not show on taskbar')'</label>
<variable>SKIPTASKBAR</variable><default>'"$SKIPTASKBAR"'</default></checkbox>
<text><label>""</label></text>
<text><label> '$(gettext 'These changes will take effect after restart')' </label></text>
<text><label>""</label></text>
</frame><frame>
<notebook labels="'$(gettext 'About|Credits|License')'">
  <frame>
   <text><label>""</label></text>
   <pixmap><input file>'"$SGRDIR"'/data/radiotray.png</input></pixmap>
   <text><label>Simple GTK Radio v0.1.18</label></text>
   <text><label>Dejan Rackovic, Copyright 2013-2014</label></text>
   <text><label>""</label></text>
   <button label="http://murga-linux.com/puppy/viewtopic.php?t=90842">
    <action>defaultbrowser http:\/\/www.murga-linux.com/puppy/viewtopic.php?t=90842 &</action>
   </button>
   <text><label>""</label></text>
  </frame>
  <vbox>
  <text><label>""</label></text>
  <text><label>Thanks to:</label></text>
  <text><label>vovchik for adding volume control and statusbar</label></text>
  <text><label>simargl for notification script</label></text>
  <text><label>Geoffrey for apearance fixes</label></text>
  <text><label>smokey01 and CatDude - suggestions and</label></text>
  <text><label>code improvements</label></text>
  <text><label>""</label></text>
  <text><label>Translators:</label></text>
  <text><label>vicmz for spanish/portuguese/italian languages</label></text>
  <text><label>robwoj44 for polish language</label></text>
  <text><label>""</label></text>
  </vbox>
  <frame>
  <text><label>""</label></text>
   <text><label>License: GPL v3</label></text>
   <text><label>""</label></text>
   <hbox homogeneous="true">
    <button label="http://www.gnu.org/licenses/gpl-3.0.html">
    <action>defaultbrowser http:\/\/www.gnu.org\/licenses\/gpl-3.0.html</action>
    </button>
   </hbox>
  </frame>
 </notebook>
</frame></notebook>
<hbox><button ok></button><button><label>'"$(gettext 'Help')"'</label><input file stock="gtk-help"></input><action>$SGRBIN help &</action></button><button cancel></button></hbox>
</vbox></window>
'

I=$IFS; IFS=""
for STATEMENTS in  $(gtkdialog4 --program=PREFS_DIAG --center); do
   eval $STATEMENTS
done
IFS=$I 

if [ "$EXIT" = "OK" ];then
echo -n "" > $SGRCONF/options
echo '#Use external editor for editing stations and viewing logs, true or false:' >> $SGRCONF/options
echo USEEDTR=\"$USEEDTR\" >> $SGRCONF/options
echo '#If above is true specify editor command:' >> $SGRCONF/options
echo EDTR=\"$EDTR\" >> $SGRCONF/options
echo '#Define time interval for auto-changer script: s for seconds, m for minutes, h for hours' >> $SGRCONF/options
echo HOWLONG=\"$HOWLONG\" >> $SGRCONF/options
echo '#For .xspf playlists only at the moment, if set to true plays first location in playlist otherwise gives choice to choose from all urls in playlist' >> $SGRCONF/options
echo PLAYFIRST=\"$PLAYFIRST\" >> $SGRCONF/options
echo '#Where to save reorded streams:' >> $SGRCONF/options
echo RIPDIR=\"$RIPDIR\" >> $SGRCONF/options
echo '#Additional parameters for streamripper, -d $RIPDIR will be added by script' >> $SGRCONF/options
echo SRIPOPTS=\"$SRIPOPTS\" >> $SGRCONF/options
echo '#Volume bar controls channel:' >> $SGRCONF/options
echo VLMCH=\"$VLMCH\" >> $SGRCONF/options
echo '#Show current station name:' >> $SGRCONF/options
echo STNENABLED=\"$STNENABLED\" >> $SGRCONF/options
echo '#Show seaparator after now playing:' >> $SGRCONF/options
echo HSENABLED=\"$HSENABLED\" >> $SGRCONF/options
echo '#Show now playing song:' >> $SGRCONF/options
echo NPENABLED=\"$NPENABLED\" >> $SGRCONF/options
echo '#Show volume control:' >> $SGRCONF/options
echo VLMENABLED=\"$VLMENABLED\" >> $SGRCONF/options
echo '#Show elapsed time statusbar:' >> $SGRCONF/options
echo STBENABLED=\"$STBENABLED\" >> $SGRCONF/options
echo '#Use window manager decorations:' >> $SGRCONF/options
echo SGRDECOR=\"$SGRDECOR\" >> $SGRCONF/options
echo '#If set to false it will not show on taskbar:' >> $SGRCONF/options
echo SKIPTASKBAR=\"$SKIPTASKBAR\" >> $SGRCONF/options
fi
;;

load)
if [ "$2" != "" ];then PLNAME="$2"
else
PLITEMS=""
for i in $SGRCONF/playlists/playlist.*;do
PLNAME=`basename $i | sed 's/playlist.//'`
PLITEMS="$PLITEMS <item>$PLNAME</item>"
done
export CHOOSEPLS='<window title="'$(gettext 'Load playlist')'" image-name="'"$SGRDIR"'/data/radiotray.png"><hbox>
<comboboxtext>
<variable>PLIST</variable>
<default>default</default>
'"$PLITEMS"'
</comboboxtext><button tooltip-text="'$(gettext 'Load')'"><input file stock="gtk-ok"></input><action>exit:OK</action></button>
<button tooltip-text="'$(gettext 'Cancel')'"><input file stock="gtk-cancel"></input><action>exit:ABORT</action></button>
</hbox></window>'

I=$IFS; IFS=""
for STATEMENTS in  $(gtkdialog4 --program=CHOOSEPLS --center); do
   eval $STATEMENTS
done
IFS=$I 

[ "$EXIT" = "OK" ] && PLNAME="$PLIST"
[ "$EXIT" = "ABORT" ] && exit
fi
[ ! -f $SGRCONF/playlists/playlist.$PLNAME ] && exit
ln -sf $SGRCONF/playlists/playlist.$PLNAME $SGRCONF/playlists/default
ln -sf $SGRCONF/playlists/playlist.$PLNAME $SGRTMP/window
echo "$PLNAME" > $SGRCONF/lastplaylist
;;

help)
if [ -f $SGRDIR/data/help.pdf ];then epdfview $SGRDIR/data/help.pdf &
else
export INSTALL_HELP='<window title="'$(gettext 'Install help')'" image-name="'"$SGRDIR"'/data/radiotray.png"><vbox>
<text><label>""</label></text>
<text wrap="true"><label>'$(gettext 'Help file not found')'</label></text>
<text><label>""</label></text>
<hbox><button label="'$(gettext 'Install')'"><action>exit:YES</action></button>
<button label="'$(gettext 'Abort')'"><action>exit:ABORT</action></button></hbox>
</vbox></window>'
I=$IFS; IFS=""
for STATEMENTS in  $(gtkdialog4 --program=INSTALL_HELP --center); do
   eval $STATEMENTS
done
IFS=$I 
[ "$EXIT" = "YES" ] && defaultbrowser http://www.murga-linux.com/puppy/viewtopic.php?t=90842 &

fi
;;

notify)
while [ "$(busybox pidof mpv)" ]; do
  
    if [ -f "$SGRTMP/mpv-output" ]; then
    
      TITLE=$(cat "$SGRTMP/mpv-output" 2>/dev/null | grep StreamTitle | sed 's|ICY Info: StreamTitle=||g' | sed 's/;[^-]*$//' | sed "s/'//g" | tail -1)
      NAME=$(cat "$SGRTMP/mpv-output" 2>/dev/null | grep "Name   :"| sed 's|Name   : ||g' 2>/dev/null)

      sleep 2s
      
      NEW_TITLE=$(cat "$SGRTMP/mpv-output" 2>/dev/null | grep StreamTitle | sed 's|ICY Info: StreamTitle=||g' | sed 's/;[^-]*$//' | sed "s/'//g" | tail -1)
      NEW_NAME=$(cat "$SGRTMP/mpv-output" 2>/dev/null | grep "Name   :"| sed 's|Name   : ||g')
      
      if [ "$NEW_TITLE" != "$TITLE" ]; then
		echo "$NEW_TITLE $NEW_NAME" > $SGRTMP/NP
        echo "$NEW_TITLE $NEW_NAME" >> $SGRTMP/radio-playlist
      fi
      
      TITLE="$NEW_TITLE"
      NAME="$NEW_NAME"
    
    fi
  done
  echo "false" > $SGRTMP/timer
  echo "Radio stopped" > $SGRTMP/NP
;;

change)
[ "$(pidof mpv)" = "" ] && echo "false" > $SGRTMP/changer && exit
SGRCH=`cat $SGRTMP/changer`
while [ "$SGRCH" = "true" ];do
SGRCH=`cat $SGRTMP/changer`
sleep $HOWLONG 
[ ! -f $SGRTMP/mpv-output ] && echo "false" > $SGRTMP/changer && exit
[ "$SGRCH" = "true" ] && $SGRBIN next 
done
;;

*)
[ ! -d $SGRTMP ] && mkdir $SGRTMP
[ ! -f $SGRTMP/NP ] && echo "$(gettext 'Radio stopped')" > $SGRTMP/NP
[ ! -f $SGRTMP/station ] && echo "$(gettext 'None')" > $SGRTMP/station
[ ! -f $SGRTMP/timer ] && echo "false" > $SGRTMP/timer
[ ! -f $SGRTMP/changer ] && echo "false" > $SGRTMP/changer
[ -f $SGRTMP/changer ] && CHANGER=`cat $SGRTMP/changer`

#Check if amixer present and get volume level
#If not present disable volume bar

if $(which amixer) >/dev/null; then
	mix_cmd=1
else
	mix_cmd=0
fi
export mix_cmd

[ "$mix_cmd" = "0" ] && [ "$VLMENABLED" = "false" ] && default_vol=75
[ "$mix_cmd" = "1" ] && default_vol=$(amixer get $VLMCH | egrep -o "[0-9]+%" | sed 's/%//')

#If toolbars below separator hidden then hide separator too
[ "$STBENABLED" = "false" ] && [ "$VLMENABLED" = "false" ] && HSENABLED="false"

export ELAPSED=$SGRTMP/elapsed
echo 0 > $ELAPSED
export MESSAGE=$SGRTMP/msg
echo "$(gettext 'Elapsed time:') 00:00:00" > $MESSAGE


# -----------------
function set_volume()
# -----------------
{
	vlmch="$1"
	myvol="$2"
	if [ "$mix_cmd" = 1 ]; then
		amixer -c 0 sset "$vlmch",0 "$myvol"% > /dev/null 2>&1&
	fi
}

# -----------------
function statusbar_update()
# -----------------
{
	SECONDS=$(($(<$ELAPSED) + 1))
	if [ $SECONDS -ge 216000 ]; then
		SECONDS=0
	fi
	echo $SECONDS > $ELAPSED
	printf "$(gettext 'Elapsed time:') %02d:%02d:%02d" $(($SECONDS / 3600)) $(($SECONDS % 3600 / 60)) $(($SECONDS % 60)) > $MESSAGE
}

# -----------------
function togglechanger()
# -----------------
{
	SGRCHANGERPID=$(ps | grep "$SGRNAME change" | grep -v grep | awk '{print $1}')
	case $1 in
		start)
			[ "$SGRCHANGERPID" = "" ] && echo "true" > $SGRTMP/changer && exec $SGRBIN change &
		;;
		stop)
		[ "$SGRCHANGERPID" != "" ] && echo "false" > $SGRTMP/changer && kill -s KILL $SGRCHANGERPID &
		;;
	esac
}

export -f togglechanger
export -f set_volume
export -f statusbar_update

[ "$PLAYLIST" = "" ] && [ -f $SGRCONF/lastplaylist ] && PLAYLIST=$(cat $SGRCONF/lastplaylist)
[ "$PLAYLIST" = "" ] && PLAYLIST="default"
[ ! -f $SGRCONF/playlists/playlist.$PLAYLIST ] && PLAYLIST="default"
ln -sf $SGRCONF/playlists/playlist.$PLAYLIST $SGRCONF/playlists/default
ln -sf $SGRCONF/playlists/playlist.$PLAYLIST $SGRTMP/window
echo "$PLAYLIST" > $SGRCONF/lastplaylist

export SGR_MAIN_DIALOG='
<window title="'$(gettext 'Simple GTK Radio')' v'"$sgrVERSION"'" resizable="true" decorated="'"$SGRDECOR"'" skip-taskbar-hint="'"$SKIPTASKBAR"'" image-name="'"$SGRDIR"'/data/radiotray.png">
 <vbox>
	<timer visible="false" auto-refresh="true">
	<input file>'"$SGRTMP"'/timer</input>
	<action>statusbar_update</action>
	<sensitive>false</sensitive>
	<action>refresh:stb0</action>
	</timer>
 <hbox homogeneous="false">
 <togglebutton relief="2" active="true" tooltip-text="'$(gettext 'Show/hide stations')'">
	<input file stock="gtk-find"></input>
	<action>if true show:STREAMURL</action>
	<action>if true show:SHOWSEARCH</action>
	<action>if false hide:STREAMURL</action>
	<action>if false hide:SHOWSEARCH</action>
</togglebutton>
<button relief="2" tooltip-text="'$(gettext 'Open URL')'">
	<input file stock="gtk-open"></input>
	<action>$SGRBIN url &</action>
</button>
<button relief="2" tooltip-text="'$(gettext 'Play')'">
	<input file stock="gtk-media-play"></input>
	<action>$SGRBIN play &</action>
</button>
<button relief="2" tooltip-text="'$(gettext 'Stop radio')'">
	<input file stock="gtk-media-stop"></input>
	<action>$SGRBIN stop &</action>
</button>
<button relief="2" tooltip-text="'$(gettext 'Play previous station')'">
	<input file stock="gtk-media-previous"></input>
	<action>$SGRBIN prev &</action>
</button>
<button relief="2" tooltip-text="'$(gettext 'Play next station')'">
	<input file stock="gtk-media-next"></input>
	<action>$SGRBIN next &</action>
</button>
<togglebutton relief="2" tooltip-text="'$(gettext 'Change stations automatically after defined interval')'" active="'"$CHANGER"'">
	<input file stock="gtk-refresh"></input>
	<action>if true togglechanger start &</action>
	<action>if false togglechanger stop &</action>
</togglebutton>
<button relief="2" tooltip-text="'$(gettext 'Add current stream to playlist')'">
	<input file stock="gtk-save"></input>
	<action>$SGRBIN save &</action>
</button>
<button relief="2" tooltip-text="'$(gettext 'Edit stations')'">
	<input file stock="gtk-edit"></input>
	<action>$SGRBIN edit &</action>
</button>
<button relief="2" tooltip-text="'$(gettext 'Show last five songs')'">
	<input file stock="gtk-about"></input>
	<action>$SGRBIN last-five &</action>
</button>
<button relief="2" tooltip-text="'$(gettext 'Preferences')'">
	<input file stock="gtk-preferences"></input>
	<action>$SGRBIN prefs &</action>
	</button>
<button relief="2" tooltip-text="'$(gettext 'Exit')'">
	<input file stock="gtk-quit"></input><action>exit:Quit</action>
</button>
</hbox>
<text visible="'"$STNENABLED"'" wrap="true" auto-refresh="true" justify="2" max-width-chars="50" height-request="30">
	<input file>'"$SGRTMP"'/station</input>
</text> 
<text visible="'"$NPENABLED"'" wrap="true" auto-refresh="true" justify="2" height-request="50">
	<input file>'"$SGRTMP"'/NP</input>
</text> 
<hseparator visible="'"$HSENABLED"'" width-request="5"></hseparator>
<hbox  visible="'"$VLMENABLED"'" height-request="50" width-request="160" homogeneous="false">
	<text xalign="1" use-markup="true" width-chars="1" width-request="50">
		<label>"<small>'$(gettext 'Volume:')'</small>"</label>
	</text>
	<hscale xalign="0" width="100" tooltip-text="'$(gettext 'Set audio output level')'" value-pos="1" space-expand="true" space-fill="true"  height-request="30" range-value="'$default_vol'">
		<variable>volume</variable>
		<action>set_volume '"$VLMCH"' "$volume"</action>
	</hscale>
</hbox>
<hbox>
 <tree column-visible="false|true" headers-visible="false" rules-hint="true" exported-column="0">
    <label>URL|Station</label>
    <height>330</height><width>400</width>
    <variable>STREAMURL</variable>
    <input file>'"$SGRTMP"'/window</input>
    <action>$SGRBIN -p "$STREAMURL" &</action>
  </tree>
</hbox>
<hbox visible="true">
<entry tooltip-text="Search streams or load playlist" activates_default="true"><variable>SEARCH</variable></entry>
<button can-default="true" has-default="true" relief="2" tooltip-text="'$(gettext 'Search streams')'">
	<input file stock="gtk-find"></input>
	<action>$SGRBIN search "$SEARCH"</action>
	<action>refresh:STREAMURL</action>
</button>
<button relief="2" tooltip-text="'$(gettext 'Save search as playlist')'">
	<input file stock="gtk-save"></input>
	<action>$SGRBIN savesearch "$SEARCH"</action>
</button>
<button relief="2" tooltip-text="'$(gettext 'Clear search results')'">
	<input file stock="gtk-clear"></input>
	<action type="clear">SEARCH</action>
	<action>ln -sf $SGRCONF/playlists/default $SGRTMP/window</action>
	<action>refresh:STREAMURL</action>
</button>
<button relief="2" tooltip-text="'$(gettext 'Load playlist')'">
	<input file stock="gtk-open"></input>
	<action>$SGRBIN load "$SEARCH"</action>
	<action>refresh:STREAMURL</action>
</button>
<variable>SHOWSEARCH</variable>
</hbox>
<hbox visible="'"$STBENABLED"'"  height-request="30" homogeneous="false">
<statusbar space-expand="true" space-fill="true" use-markup="true" has-resize-grip="false" auto-refresh="true">
	<variable>stb0</variable>
	<input file>'$MESSAGE'</input>
</statusbar></hbox>
</vbox>
</window>
'

gtkdialog4 --program=SGR_MAIN_DIALOG

togglechanger stop &
$SGRBIN stop &
;;

esac

##END##
