#!/bin/bash
#pMusic
#Copyright 2008,2009,2010,2011,2012,2013,2014,2015
#Sigmund Berglund - Valåmoen, Norway.

#------------------------------
#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 version 2.

#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. <http://www.gnu.org/licenses/>.
#------------------------------

VERSION="4.7.2" #REMEMBER to set version in $APPDIR/pmusicrc
export AUDIO_FORMATS="\.aac$|\.ac3$|\.aif$|\.aiff$|\.ape$|\.asf$|\.au$|\.flac$|\.gsm$|\.kar$|\.m4a$|\.mid$|\.mp1$|\.mp2$|\.mp3$|\.mp4$|\.mpc$|\.ogg$|\.ra$|\.raw$|\.shn$|\.voc$|\.wav$|\.wma$|\.wv$"
type pequalizer > /dev/null 2>&1 && pequalizer -s & #setup initial presets
export GTKDIALOG=gtkdialog
export UTF8=false #Set false to make searching (grep) work with LC_ALL=C. This makes grep _much_ faster working with the db. The downside is 'grep -i' non-english chars will be case sensitive.
export TXT_SEARCHING="$(gettext 'Searching more info')"
export TXT_NO_CONNECTION="$(gettext 'Not able to connect to internet')"
#gettext
export TEXTDOMAIN=pmusic
export OUTPUT_CHARSET=UTF-8

#Ftp settings to grab index files and faq...
export FTP_SERVER='http://www.01micko.com/zigbert/pmusic'
export FTP_USER='puppy'
export FTP_PASSWORD='linux'
export FTP_SERVER_2='http://www.meownplanet.net/zigbert/pmusic'
export FTP_USER_2='puppy'
export FTP_PASSWORD_2='linux'
export PING_SERVER='google.com'
export PLUGIN_URL='http://murga-linux.com/puppy/viewtopic.php?t=82014'

#define pmusic application path
export APPDIR=`dirname $0`
[ $APPDIR = '.' ] && export APPDIR=`pwd`

#setup config file
export CONFIG=$HOME/.pmusic/pmusicrc

#pMusic work-dir
export WORKDIR=$HOME/.pmusic/tmp
[ ! -d $WORKDIR ] && FIRST_RUN=true
[ ! -d $WORKDIR ] && mkdir -p $WORKDIR #makes all dirs in path

#stderr
export STDERR=$WORKDIR/stderr #--debug will change this to stderr
echo -n > $WORKDIR/stderr

#version upgrade
if [ "`grep -F VERSION $CONFIG 2> /dev/null | cut -d= -f2`" != "$VERSION" ] || [ ! -s $CONFIG ]; then
	#Fresh start if previous pmusic installation is older than version 4.0.0
	if [ "`grep -F VERSION $CONFIG  2> $STDERR | cut -d= -f2 | cut -d. -f1`" -lt 4 2> $STDERR ]; then
		rm -f $WORKDIR/*
		VERSION_UPGRADE=true
	fi
	#fill in new vaiables missing in $CONFIG
	. $APPDIR/pmusicrc
	#read rc
	[ ! -s $CONFIG ] && cp $APPDIR/pmusicrc $CONFIG
	. $CONFIG
	#---
	. $APPDIR/func_config -version_upgrade
	$APPDIR/func_svg -splash > /dev/null #this is static, so we don't build this one until a new upgrade
else
	#read rc
	. $CONFIG
fi

export LANGUAGE="$MY_LANGUAGE"
[ "$MY_LANGUAGE" = "auto" ] && export LANGUAGE="${LANG%%_*}"
#export LANG=$LANGUAGE #deactivating UTF-8 makes grep db much slower. This affect many aspects - searching, trackinfo, most_played, ...

echo $APPDIR > $WORKDIR/APPDIR
echo "pMusic $VERSION" > $WORKDIR/window_title
echo false > $WORKDIR/DONT_SAVE_FRONTEND #if -j switch was used last run, this file could be true
#be sure to close message if user restarts pMusic
echo 0 > $WORKDIR/maingui_notebook_page
[ -f $HOME/.pmusic/nowplaying_albumart.jpg ] && cp -f $HOME/.pmusic/nowplaying_albumart.jpg $WORKDIR/albumart.jpg || cp -f "$APPDIR/themes/$THEME/album_art.svg" $WORKDIR/albumart.jpg

#reset Conditional Widget Refreshing
echo false > $WORKDIR/UPDATE_PLAYLIST
echo false > $WORKDIR/UPDATE_TRACKINFO
echo false > $WORKDIR/UPDATE_SOURCELIST
echo false > $WORKDIR/UPDATE_SOURCELIST2
echo false > $WORKDIR/UPDATE_GUI

#first run
if [ "$FIRST_RUN" = "true" ] || [ "$VERSION_UPGRADE" = "true" ]; then
	echo "$(gettext 'First run - initialising')" > $WORKDIR/splashtext
	$APPDIR/box_splash 2> $STDERR & #avoid terminal outputs on first run
	#update db
	[ ! -s "$STORAGE_DIR"/index_directories ] && echo -e "$HOME\n/mnt\n" > "$STORAGE_DIR"/index_directories
	$APPDIR/func_index -msg_quick_update &
	[ "`grep -F '/' <<< "$*"`" ] && echo > $WORKDIR/flag_fix_db #avoid quick_index-msg in main gui at check_source in func_add.
	#---
	$APPDIR/func_svg -nowplaying "pMusic $VERSION" &
	$APPDIR/func -statusbar_playlist & #make sure the statusbar shows active playlist
	#check if valid theme - pMusic 4 requires svg based graphics
	[ ! -f $APPDIR/themes/$THEME/icon_play.svg ] && export THEME="Gtk"
	echo -n > $WORKDIR/heading.svg #only to avoid terminal output from 'func -set_gtk'
	#avoid terminal output from 'func_player'
	[ ! -f $WORKDIR/ffmpeg_filter_EQ ] && echo -n > $WORKDIR/ffmpeg_filter_EQ
	[ ! -f $WORKDIR/ffmpeg_filter_basic ] && echo -n > $WORKDIR/ffmpeg_filter_basic
	[ ! -f $WORKDIR/ffmpeg_filter ] && echo -n > $WORKDIR/ffmpeg_filter
	#---
	[ ! -f $WORKDIR/playlist ] && echo -n > $WORKDIR/playlist #content of the pMusic playlist
	[ ! -f $WORKDIR/PLAYLIST ] && echo -n > $WORKDIR/PLAYLIST #the variable $PLAYLIST
	[ ! -f $WORKDIR/sourcelist ] && echo -n > $WORKDIR/sourcelist
	[ ! -f $WORKDIR/radiohits_presets ] && echo -n > $WORKDIR/radiohits_presets
	[ ! -f "$STORAGE_DIR"/index_mymusic ] && echo -n > "$STORAGE_DIR"/index_mymusic 
	[ ! -f "$STORAGE_DIR"/index_recent ] && echo -n > "$STORAGE_DIR"/index_recent 
	[ ! -s "$STORAGE_DIR"/index_history ] && echo -n > "$STORAGE_DIR"/index_history
	echo 0 > $WORKDIR/statusbar_error #see func_progressbar
	echo 0 > $WORKDIR/VOLUME #will be updated after gui-load
	echo 0 > $WORKDIR/BALANCE #will be updated after gui-load
	echo 0 > $WORKDIR/PERCENT_BAR #value (percent) of progress. see func_progressbar
	echo 0 > $WORKDIR/SS #starting point (in seconds) of playing track.
	echo tail > $WORKDIR/ADDMODE #add next track at the end of playqueue
	[ ! -d "$STORAGE_DIR/favorite_lists" ] && mkdir "$STORAGE_DIR/favorite_lists"
	[ ! -d "$STORAGE_DIR/history_files" ] && mkdir "$STORAGE_DIR/history_files"
	[ ! -d "$STORAGE_DIR/podcasts" ] && mkdir "$STORAGE_DIR/podcasts"
	[ ! -s "$STORAGE_DIR"/favorites ] && echo -e "$HOME/|$(gettext 'Home directory')|||||||||||||gtk-directory\n$STORAGE_DIR/podcasts/|$(gettext 'Podcast Storage')|||||||||||||gtk-directory_podcast\npmusic_top100|Jamendo Top100|||||||||||||gtk-audio_playlist" > "$STORAGE_DIR"/favorites
	[ ! -s "$STORAGE_DIR/favorite_lists/My favorite list.pmd" ] && echo 'http://api.jamendo.com/get2/stream/track/redirect/?streamencoding=mp31&id=859743|Hoovers|Let me be there in the morning|Take me home|6|2005||||||05:52||http://api.jamendo.com/get2/stream/track/redirect/?streamencoding=mp31&id=859743|gtk-audio' > "$STORAGE_DIR/favorite_lists/My favorite list.pmd"
	#default add-list
	export SOURCE=$BROWSERDIR
	$APPDIR/func -browse
	gettext 'Search for music' > $WORKDIR/filebrowser_dir #we want this info instead of the browsing path that will normally show up.
	#show icon for album art
	[ ! -f $HOME/.pmusic/nowplaying_albumart.jpg ] && cp -f $APPDIR/themes/$THEME/album_art.svg $HOME/.pmusic/nowplaying_albumart.jpg 2> $STDERR 
	[ ! -f $WORKDIR/trackinfo_albumart.jpg ] && cp -f $APPDIR/themes/$THEME/album_art.svg $WORKDIR/trackinfo_albumart.jpg 2> $STDERR
	[ ! -f $WORKDIR/albumart.jpg ] && cp -f $APPDIR/themes/$THEME/album_art.svg $WORKDIR/albumart.jpg 2> $STDERR
	#define playmode
	echo straight > $WORKDIR/PLAYMODE #loop gives not wanted behaviour if pmusic is used as default audioplayer
	cp -f $APPDIR/themes/$THEME/icon_playmode_straight.svg $WORKDIR/icon_playmode.svg
	#start song to offer at least one music track :) 
	LANG=C wget --spider --tries 1 $PING_SERVER 2> $WORKDIR/tmp #check connection
	if [ "`grep 'connected' $WORKDIR/tmp`" ]; then
		echo -e '|05:52|Hoovers - Let me be there in the morning|http://api.jamendo.com/get2/stream/track/redirect/?streamencoding=mp31&id=859743|00001 http://api.jamendo.com/get2/stream/track/redirect/?streamencoding=mp31&id=859743' > $WORKDIR/playlist
	fi
	#Puppy...
	#add mime type
	if [ ! "`grep -F 'x-pmusic' /usr/share/mime/globs`" ]; then
		echo 'audio/x-pmusic:*.pmu' >> /usr/share/mime/globs
		[ ! -d $HOME/.config/rox.sourceforge.net/MIME-types ] && mkdir $HOME/.config/rox.sourceforge.net/MIME-types
		echo -e '#! /bin/sh\nexec pmusic "$@"' > $HOME/.config/rox.sourceforge.net/MIME-types/audio_x-pmusic
		chmod 755 $HOME/.config/rox.sourceforge.net/MIME-types/audio_x-pmusic
	fi
	#give pmusic executable an icon in Rox
	rox --RPC << EOF
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://www.w3.org/2001/12/soap-envelope">
 <env:Body xmlns="http://rox.sourceforge.net/SOAP/ROX-Filer">
  <SetIcon>
   <Path>/usr/local/pmusic/pmusic</Path>
   <Icon>/usr/share/icons/hicolor/scalable/apps/pmusic.svg</Icon>
  </SetIcon>
 </env:Body>
</env:Envelope>
EOF
	#update gtk icon cache to activate pmusic icon in /usr/share/icons/hicolor/scalable/apps/
	gtk-update-icon-cache -f -i /usr/share/icons/hicolor 2> $STDERR
	echo 100 > $WORKDIR/splash
else
	#if db is empty
	if [ ! -s "$STORAGE_DIR"/index_mymusic ]; then
		$APPDIR/func_index -msg_quick_update &
		echo > $WORKDIR/flag_fix_db #avoid quick_index-msg in main gui at next check_source in func_add.
	fi
	#---
	[ $# = 0 ] && gettext 'Search for music' > $WORKDIR/filebrowser_dir #no parameters is used
fi

[ ! "`ls -1 /sys/block 2> $STDERR | grep -E '^scd|^sr' | tr '\n' ' '`" ] && export CD_DEV=false

#reset frontend specific options before reading parameters
OVERRIDE_PMUSIC_FRONTEND='' #NowPlaying returns this value, and we need to clear it for an ordinary run

#parameters
while [ $# != 0 ]; do
	I=1
	while [ $I -lt `echo $# | wc -c` ]; do
		if [ -d "$1" ]; then #add content of directory
			if [ "$RECURSIVE" ]; then MAXDEPTH=100; else MAXDEPTH=1; fi
			find "$1" -maxdepth $MAXDEPTH -name "*" -type f -printf "||%p\n" | grep -iE "$AUDIO_FORMATS" > $WORKDIR/pmusic.add
			export SOURCE=$WORKDIR/pmusic.add
			if [ ! "$ADD_FILE" ]; then $APPDIR/func_store_playlist; $APPDIR/func -new; fi #save last playlist 
			. $APPDIR/func_add -add
			export ADD_FILE=true #in case user wants to add more than 1 song
			sleep 0.2 #be sure the splash screen is gone
		elif [ "`echo "$1" | grep -F '/'`" ]; then #try to open ALL files and URLs
			if [ "$JUST_PLAY" = "true" ]; then # -B switch is used. play as fast as possible
				ffmpeg -i "$1" 2> $WORKDIR/tmp
				LENGTH=`grep Duration $WORKDIR/tmp | awk '{print $2}' | cut -d"." -f1 | cut -d":" -f2-`
				[ "$LENGTH" = "N/A," ] && LENGTH='00:00'
				#build command --- split echos to ensnure filenames that contaions ' will play
				echo '#!/bin/sh' > $WORKDIR/exec
				if [ "$LENGTH" = "00:00" ] || [ "$LENGTH" = "00:01" ] && [ ! "`grep -F '://' $WORKDIR/PLAYLIST`" ]; then #if length is under 2 sec --> piping ffmpeg | aplay fails
					echo -n "ffmpeg -i '" >> $WORKDIR/exec
					echo -n "${1}" | sed s/\'/\'\"\'\"\'/g >> $WORKDIR/exec #if filename contains ' this won't play else we put it into ""
					echo "' -f au -y $WORKDIR/pmusic.au"  >> $WORKDIR/exec
					echo "aplay $WORKDIR/pmusic.au" >> $WORKDIR/exec
				else #Normal way
					echo -n "exec ffmpeg -i '" >> $WORKDIR/exec
					echo -n "${1}" | sed s/\'/\'\"\'\"\'/g >> $WORKDIR/exec #if filename contains ' this won't play else we put it into ""
					echo "' -f au - | aplay" >> $WORKDIR/exec
				fi
				chmod 700 $WORKDIR/exec
				$WORKDIR/exec 2> $STDERR
				exit
			else #add to playlist, index databases.... before playing. (use the ordinary playing structure)
				if [ "`echo "$1" | grep "^\./"`" ] || [ ! "`echo "$1" | grep -F "/"`" ]; then #path is not specified, -> use current
					TMP="`basename "$1"`"
					J="`pwd`/$TMP"
				else 
					J="$1"
				fi
				#if no gui is up and running, prepare selected file to be played
				if [ ! "$ADD_FILE" ] && [ ! -f $WORKDIR/gui_is_running ]; then
					$APPDIR/func_store_playlist
					$APPDIR/func -new
				fi
				. $APPDIR/func_add -add "$J"
				export ADD_FILE=true #in case user wants to add more than 1 song
			fi
		fi
		case $1 in
			-a)	export ADD_FILE=true;;
			-b) NOGUI=true; RUN_PLUGIN_AT_START=false;;
			-B) $APPDIR/func_player -stop -skip_update; JUST_PLAY=true;;
			-c) #if used in combination with the -j switch, Keep -j before -c
				$APPDIR/func_store_playlist
				$APPDIR/func_cd -play_cd &
				RUN_CD=true #only used later in this script for first-run check
				;;
			-D) echo -e "  \e[04mR E Q U I R E D                            \e[0m"
				echo -n '    bash                                      '
				if type bash > /dev/null 2>&1; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;31m[MISSING]\e[0m"; fi
				echo -n '    coreutils, awk, sed, diff                 '
				if type cp > /dev/null 2>&1 && type awk > /dev/null 2>&1 && type sed > /dev/null 2>&1 && type diff > /dev/null 2>&1; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;31m[MISSING]\e[0m"; fi
				#gtkdialog
				TMP=`$GTKDIALOG --version | grep -F version | cut -d' ' -f3`
				echo -n '    gtkdialog                        >= r512  '
				if type gtkdialog > /dev/null 2>&1 && [ "`echo $TMP | tr -d '.'`" -ge 084 ]; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;31m[MISSING]\e[0m"; fi
				#ffmpeg is not that straight forward since compiling from git gives another output
				TMP=`ffmpeg -version 2> $STDERR | grep -iF 'ffmpeg' | cut -d' ' -f3`
				echo -n '    ffmpeg                                    '
				if type ffmpeg > /dev/null 2>&1; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;31m[MISSING]\e[0m"; fi
				#---
				echo -n '    aplay  (alsa)                             '
				if type aplay > /dev/null 2>&1; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;31m[MISSING]\e[0m"; fi
				echo -e "\n  \e[04mR E C O M M E N D E D                      \e[0m"
				echo -n '    streamripper (extended radio-rip/play)    '
				if type streamripper > /dev/null 2>&1; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;36m[MISSING]\e[0m"; fi
				echo -n '    cdda2wav     (play/rip audio-CD)          '
				if type cdda2wav > /dev/null 2>&1; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;36m[MISSING]\e[0m"; fi
				echo -n '    wget         (connection to www)          '
				if type wget > /dev/null 2>&1; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;36m[MISSING]\e[0m"; fi
				echo -e "\n  \e[04mO P T I O N A L                            \e[0m"
				echo -n '    pBurn        (burning audio-CD)           '
				if type pburn > /dev/null 2>&1; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;36m[MISSING]\e[0m"; fi
				echo -n '    pFilesearch  (File-search engine) >= 1.28 '
				#pfilesearch
				TMP=`pfilesearch -v | cut -d' ' -f2 | tr -d '.' | cut -c1-2` #may have 2 or 3 chars
				if type pfilesearch > /dev/null 2>&1 && [ $TMP -ge 13 ]; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;36m[MISSING]\e[0m"; fi
				#pschedule
				echo -n '    pSchedule    (podcast managing)   >= 1.12 '
				TMP=`pschedule -v | cut -d' ' -f2 | tr -d '.'`
				if type pschedule > /dev/null 2>&1 && [ $TMP -ge 112 ]; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;36m[MISSING]\e[0m"; fi
				echo -n '    pEqualizer   (10 band equalizer)          '
				if type pequalizer > /dev/null 2>&1; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;36m[MISSING]\e[0m"; fi
				echo -n '    Timidity     (play midi)                  '
				if type timidity > /dev/null 2>&1; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;36m[MISSING]\e[0m"; fi
				echo -n '    libcddb      (improved CD detection)      '
				if type cddb_query > /dev/null 2>&1; then echo -e "\e[01;32m[OK]\e[0m"; else echo -e "\e[01;36m[MISSING]\e[0m"; fi
				exit
				;;
			--debug) export STDERR=/dev/stderr; DEBUG=true;;
			--dump-gtk) DUMP_GTK=true;;
			-f) echo -e "$AUDIO_FORMATS\n  asx (read only)\n  m3u\n  pls\n  pmu\n" | tr -d '$' | tr '\' ' ' | tr '.' ' ' | tr '|' '\n' | sed -e 's%mid%mid (requires timidity)%' -e 's%kar%kar (requires timidity)%'
				exit
				;;
			-i) case $2 in
					albumart)	defaultimageviewer $HOME/.pmusic/nowplaying_albumart.jpg;;
					nowplaying)	cut -d'|' -f1 $HOME/.pmusic/nowplaying;;
					path)		cut -d'|' -f2 $HOME/.pmusic/nowplaying;;
					*) 			echo 'pMusic error: Unknown info';;
				esac
				exit 0;;
			-j) cp -f $WORKDIR/playlist $WORKDIR/playlist.bak #don't interfere with default playlist. Copy back in func -quit
				echo true > $WORKDIR/DONT_SAVE_FRONTEND 2> $STDERR
				;;
			-p) OVERRIDE_PMUSIC_FRONTEND="$2"
				#remove $WORKDIR/xml_pmusic if not using the -j switch
				if [ "`echo "$*" | grep -F ' -j'`" ] || [ "$(<$WORKDIR/DONT_SAVE_FRONTEND)" ]; then
					true
				else
					rm $WORKDIR/xml_pmusic
				fi
				shift;;
			-P) export ENSURE_PLAY=true;;
			-r) RECURSIVE=true;;
			--reset)
				rm -fr $WORKDIR
				pmusic &
				exit 0;;
			-s) case $2 in
					mute) 		$APPDIR/func_mixer -mute;;
					next) 		#cp -f $WORKDIR/PLAYLIST $WORKDIR/tmpPLAYLIST #RATING:to remember what was played (decrease rating)
								$APPDIR/func_player -next;;
					pause) 		$APPDIR/func_player -play -skip_update;;
					prev) 		$APPDIR/func_player -back;;
					quit) 		$APPDIR/func -quit;;
					stop) 		$APPDIR/func_player -stop -skip_update;;
					volup) 		$APPDIR/func_mixer -volume_up;;
					voldown)	$APPDIR/func_mixer -volume_down;;
					balleft) 	$APPDIR/func_mixer -balance_left;;
					balright)	$APPDIR/func_mixer -balance_right;;
					*) 			echo 'Pmusic error: Unknown signal';;
				esac
				exit 0;;
			-t) MIN=`echo $2 | cut -d':' -f1`
				SEC=`echo $2 | cut -d':' -f2`
				echo "$[($MIN*60)+$SEC]" > $WORKDIR/SS
				echo true > $WORKDIR/TIMESTAMP
				shift
				;;
			-T)	THEME="$2"
				shift
				;;
			-u)	. $CONFIG
				echo 'check new podcasts'
				$APPDIR/func_podcast -u
				exit
				;;
			-U)	export UPDATE_INTERVAL=$2
				;;
			-v|--version) echo pMusic $VERSION; exit;;
			-h|--help)
				echo 'Usage: pmusic [OPTION(S)] [FILE(S) / DIR(S) / URL(S)]

				'  "'"pmusic /path/file.mp3"'"' will add file to playqueue if pmusic is already
				  running. If not running, pmusic will start with empty playqueue and play file.
				  To override this dynamic behavior, use the -a/-P switch.

				Options
				  -a             Add [FILE(S) / DIR(S) / URL(S)] to playqueue instead of playing it
				  -b             Use pMusic as backend - no GUI
				  -B             Use only backend - do not interfere with playqueue, etc.
				                 This works as a dead simple command-line player
				  -c             Loads CD-audio disc into playqueue and starts playing
				  -D             List pMusic dependencies and if installed on your system
				      --debug    Show debugging messages
				      --dump-gtk Print the gtk-code (xml) and exit
				  -f             List supported audio formats
				  -h, --help     Show this help message
				  -i INFO        Show info about playing track
				                   albumart   - show album art in defaultimageviewer
				                   nowplaying - Return playing artist - title
				                   path       - Return full path of playing track
				  -j             Do NOT save PMUSIC_FRONTEND settings (like geometry, ...)
				                 Handy in combination with -p
				  -p FRONTEND    Use this frontend instead of the one defined in rc
				                 Available frontends are stored in '$APPDIR'/frontends/
				  -P             Ensure that the defined file will start playing
				  -r             Add all supported files in directories recursively
				      --reset    Start pMusic like a fresh install.
				                 But keep most personal settings.
				  -s SIGNAL      Send signal to a running instance of pMusic
				                   balleft    - increase balance left by 10%
				                   balright   - increase balance right by 10%
				                   mute       - Turn volume On/Off 
				                   next       - Play next song in playqueue
				                   pause      - Pause/Play audio
				                   prev       - Play previous song in playqueue
				                   quit       - Quit all pmusic processes
				                   stop       - Stop playing
				                   volup      - increase volume by 10%
				                   voldown    - derease volume by 10%
				  -t xx:xx       Set the start time offset
				                 This does not work with the -a switch
				  -T THEME       Set graphical theme for this instance only 
				  -u             Update podcasts
				  -U MILLISEC    Set update interval for progressbar +++
				                 This is useful to reduce cpu-hunger on low-powered systems
				                 Default is 1000 = 1 sec
				  -v, --version  Show pMusic version
				  
				Supported formats (with working alsa and ffmpeg)'"
				`echo -e "  \e[0mWAVE\n  \e[03m$AUDIO_FORMATS" | tr -d '$' | tr '\' ' ' | tr '.' ' ' | tr -d '|' | sed -e 's%  mid%%' -e 's%  kar%%'
				echo -e "  \e[0mPLAYLIST\n    \e[03mpmu  m3u  pls  asx\e[0m\n  \e[0mMIDI (requires timidity)\n    \e[03mmid  kar\e[0m"`
				
				Dependencies"
				echo "`pmusic -D`" | tr -d '\011'; exit;; #\011 --> remove tabs
		esac
		shift
		I=$(($I+1))
	done
done

#check if gui exist (open/add from terminal) --> add and quit.
if [ -f $WORKDIR/gui_is_running ] && [ "$ADD_FILE" ]; then
	echo true > $WORKDIR/UPDATE_GUI
	exit 0
fi

#check for data storage
if [ ! "$STORAGE_DIR" ] && [ ! -d "$STORAGE_DIR" ]; then TXT1="$(gettext 'Data Storage are not there. Either it does not exist, or it is not mounted. Data Storage is set in the preferences.')"; . $APPDIR/box_ok; fi

#set frontend
[ "$OVERRIDE_PMUSIC_FRONTEND" ] && export PMUSIC_FRONTEND=$OVERRIDE_PMUSIC_FRONTEND
if [ -f "$APPDIR/frontends/$PMUSIC_FRONTEND" ]; then
	export PMUSIC_FRONTEND="$APPDIR/frontends/$PMUSIC_FRONTEND"
elif [ -f "$PMUSIC_FRONTEND" ]; then
	false
else
	export PMUSIC_FRONTEND="$APPDIR/frontends/Manager"
fi

#kill older instances of pmusic, and if gtkdialog didn't quit properly
kill -9 `cat $WORKDIR/MY_PID 2> $STDERR` 2> $STDERR
echo $$ > $WORKDIR/MY_PID #store for next instance (new PMUSIC_FRONTEND or new startup without quit)
ps -eo pid,command > $WORKDIR/tmp
for I in `grep -i pmusic $WORKDIR/tmp | grep -E "gtkdialog|update_index|func_progressbar" | grep -vF radiohits | awk '{print $1}'`; do kill -9 $I 2> $STDERR; done
#clean up text in statusbar
! grep aplay $WORKDIR/tmp > /dev/null && rm -f $WORKDIR/ffmpeg_output

#more first_run - this will only run if gui shows up. It might be that first run is with parameters like --version.
if [ "$FIRST_RUN" = "true" ] || [ "$VERSION_UPGRADE" = "true" ] && [ "$RUN_CD" != "true" ] && [ ! -s $WORKDIR/AUTOPLAY ]; then #do not run this if -c switch is used
	echo true > $WORKDIR/AUTOPLAY #lock this 
	$APPDIR/func_player -play -skip_update &
fi

#show play or pause button (if present in theme)
[ -f $APPDIR/themes/$THEME/icon_play.svg ] && cp -f $APPDIR/themes/$THEME/icon_play.svg $WORKDIR/icon_playpause.svg
ps -eo pid,s,command > $WORKDIR/tmp
[ "`grep aplay $WORKDIR/tmp | grep ' S '`" ] && [ -f $APPDIR/themes/$THEME/icon_pause.svg ] && cp $APPDIR/themes/$THEME/icon_pause.svg $WORKDIR/icon_playpause.svg 2> $STDERR #playing

#Check if plugins are set to autostart
for I in `find $APPDIR/plugins/ -name "*.rc" -printf "%f\n"`; do
	. $APPDIR/plugins/$I
	if [ "$PLUGIN_RUN_AT_START" = "true" ]; then
		TMP="`ps`"
		[ ! "`echo "$TMP" | grep -F $PLUGIN_EXEC`" ] && exec $APPDIR/plugins/$PLUGIN_EXEC &
	fi
done

if [ "$NOGUI" != "true" ]; then
	#use a unique xml-file for temporary guis (-j switch) to avoid conflict with the xml-backup feature
	if [ "$(<$WORKDIR/DONT_SAVE_FRONTEND)" = "true" ]; then
		XML_SUFFIX='_tmp'
	else
		rm -f $WORKDIR/xml_pmusic_tmp #guis that is not permanent (ie CD-player and Radio streamer). This file is describing the active frontend when temporary
		XML_SUFFIX=''
	fi

	#run unique commands/settings to override default settings
	[ -s ${PMUSIC_FRONTEND}.pre ] && . ${PMUSIC_FRONTEND}.pre
	#build gui if not in xml_pmusic file
	if [ "`diff $WORKDIR/xml_pmusic $WORKDIR/xml_pmusic.bak 2> /dev/null`" ] || [ ! -f $WORKDIR/xml_pmusic ] || [ ! -f $WORKDIR/xml_pmusic.bak ] || [ "$OVERRIDE_PMUSIC_FRONTEND" ]; then
		. $PMUSIC_FRONTEND
		[ $TOOLTIPS = false ] && GUI="`echo "$GUI" | sed -e 's%tooltip-text%tooltipXXXtext%g' -e 's%tooltip-column%tooltipXXXcolumn%g'`" #deactivate tooltips
		echo "$GUI" | sed 's/##.*//' > $WORKDIR/xml_pmusic${XML_SUFFIX} #I use double hash (##) for comments. --> as #FF0000 is valid xml-code
		cp -f $WORKDIR/xml_pmusic $WORKDIR/xml_pmusic.bak #does not backup xml_pmusic${XML_SUFFIX} as this one is for temporary guis only
	fi

	if [ "$(<$WORKDIR/DONT_SAVE_FRONTEND)" != "true" ]; then
		#include <window> tag here to always keep track of geometry, - Pmusic only updates xml-code if frontend has changed.
		[ ! "`grep -F '<window' $WORKDIR/xml_pmusic.bak`" ] && echo '<window allow-shrink="true" icon-name="pmusic" default_height="'$HEIGHT'" default_width="'$WIDTH'">'"$(<$WORKDIR/xml_pmusic.bak)" > $WORKDIR/xml_pmusic.bak
		[ ! "`grep -F '<window' $WORKDIR/xml_pmusic`" ] && echo '<window allow-shrink="true" icon-name="pmusic" default_height="'$HEIGHT'" default_width="'$WIDTH'">'"$(<$WORKDIR/xml_pmusic)" > $WORKDIR/xml_pmusic
	fi
	#start pequalizer if included in gui
	[ "`grep -F 'pequalizer/preset' $WORKDIR/xml_pmusic`" ] && mv -f $HOME/.asoundrc.bak $HOME/.asoundrc 2> $STDERR
	#run gui
	if [ "$DUMP_GTK" = "true" ]; then cat $WORKDIR/xml_pmusic${XML_SUFFIX}; $APPDIR/func -quit; exit 0; fi
	#set GTK theme
	. $APPDIR/func -set_gtk
	#in case huge sourcelist...
	[ "`cat $WORKDIR/sourcelist | wc -l`" -gt 1000 ] && $APPDIR/func_favorites -show_favorites
	#---
	$GTKDIALOG -f $WORKDIR/xml_pmusic${XML_SUFFIX} -G +"$X"+"$Y" 2> $STDERR &

	sleep 1
	#error-check
	if [ "`grep -F 'gtkdialog: Error in line' $WORKDIR/stderr`" ]; then
		rm $WORKDIR/xml_pmusic*
		echo
		echo '=========================================='
		echo "Gtkdialog $(gettext 'failed to run the pMusic frontend')"
		echo "$(gettext "Please execute 'pmusic -D' to check all dependencies.")"
		$APPDIR/func -quit
	fi
fi

exit 0
