#!/bin/bash
#pMusic
#Copyright 2008,2009,2010,2011,2012,2013,2014
#Sigmund Berglund
IFS=$'\n'
export TEXTDOMAIN=pmusic
export TEXTDOMAINDIR=/usr/share/locale
export OUTPUT_CHARSET=UTF-8

AUDIO_FORMATS2="`echo "$AUDIO_FORMATS" | sed 's/\\$/\\\|/g'`" #example: |/path/file.mp3|

template (){
	COUNT=1
	for J in "$(gettext 'Command')" "$(gettext 'Artist / Filename')" "$(gettext 'Title')" "$(gettext 'Album')" "$(gettext 'Nr')" "$(gettext 'Year')" "$(gettext 'Genre')" "$(gettext 'Comment')" "$(gettext 'Rate')" "$(gettext 'Format')" "$(gettext 'Kb/s')" "$(gettext 'Length')" "$(gettext 'Not in use')" "$(gettext 'Path')" "$(gettext 'Icon')" "$(gettext 'Disc-ID') musicbrainz.org" "$(gettext 'Artist-ID') musicbrainz.org" "$(gettext 'Lyrics source')" "$(gettext 'Album-art source')" "$(gettext 'Not in use')" "$(gettext 'Timestamps')"; do
		case $1 in
		-first)
			echo '
			<action>cut -d"|" -f'$COUNT' '$WORKDIR'/tmp_index > '$WORKDIR'/tmp_db_'$COUNT'</action>
			<action>refresh:DB_'$COUNT'</action>'
			;;
		-second)
			echo '
			<hbox>'
			 if [ "`grep -E "^$(gettext 'Not in use')$" <<< "$J"`" ]; then
				echo '<text use-markup="true"><label>"<b>   </b>'$J'"</label><sensitive>false</sensitive></text>'
			 elif [ "`grep -E "^$(gettext 'Artist / Filename')$|^$(gettext 'Title')$|^$(gettext 'Album')$|^$(gettext 'Nr')$|^$(gettext 'Year')$|^$(gettext 'Genre')$|^$(gettext 'Comment')$|^$(gettext 'Rate')$|^$(gettext 'Not in use')$|^$(gettext 'Icon')$" <<< "$J"`" ]; then
				echo '<text use-markup="true"><label>"<b>   </b>'$J'"</label></text>'
			 else
				echo '<text use-markup="true"><label>"<b>   '$J'</b>"</label></text>'
			 fi
			 echo '
			 <entry>
			  <variable>DB_'$COUNT'</variable>
			  <input file>'$WORKDIR'/tmp_db_'$COUNT'</input>'
			  if [ "`grep -E "^$(gettext 'Not in use')$" <<< "$J"`" ]; then echo '<sensitive>false</sensitive>'; fi
			  #[ "`grep -E "$(gettext 'Rate')|$(gettext 'Not in use')|$(gettext 'Icon')" <<< "$J"`" ] && echo '<sensitive>false</sensitive>'
			 echo '</entry>
			</hbox>'
			;;
		-third)
			echo -n > $WORKDIR/tmp_db_$COUNT
			;;
		-fourth)
			echo '<action>clear:DB_'$COUNT'</action>'
			;;
		esac
		COUNT=$(($COUNT+1))
	done
}

save_db (){
	[ ! "$DB" ] && exit
	echo "$DB_1|$DB_2|$DB_3|$DB_4|$DB_5|$DB_6|$DB_7|$DB_8|$DB_9|$DB_10|$DB_11|$DB_12|$DB_13|$DB_14|$DB_15|$DB_16|$DB_17|$DB_18|$DB_19|$DB_20|$DB_21" > $WORKDIR/tmp_index
	( flock -e 200
		grep -v "^${DB_1}|" "$STORAGE_DIR/index_mymusic" >> $WORKDIR/tmp_index
		mv $WORKDIR/tmp_index "$STORAGE_DIR/index_mymusic"
	) 200>$WORKDIR/mymusic_db.lockfile 
}

delete_db (){
	[ ! "$DB" ] && exit
	FRAME="$(gettext 'Delete')"; IMG="delete"; TXT1="$(gettext 'Delete DB item?')"; TXT2="$DB"
	. $APPDIR/box_yesno
	if [ $EXIT = "yes" ]; then
		( flock -e 200
			grep -v "^${DB_1}|" "$STORAGE_DIR/index_mymusic" > $WORKDIR/tmp_index
			mv $WORKDIR/tmp_index "$STORAGE_DIR/index_mymusic"
		) 200>$WORKDIR/mymusic_db.lockfile 
	fi
}

export -f template save_db delete_db



case "$1" in
-search_db)
	IFS=" "
	echo '' > "$STORAGE_DIR"/index_mymusic.editor
	echo -n "cat \"$STORAGE_DIR/index_mymusic\"" > $WORKDIR/tmp_index_exec
	for I in $2; do TMP="`echo "$I" | sed 's%"%\\\\\"%g'`"; echo -n "| grep -iF \"$TMP\" " >> $WORKDIR/tmp_index_exec; done
	echo " > \"$STORAGE_DIR/index_mymusic.editor\"" >> $WORKDIR/tmp_index_exec
	chmod 722 $WORKDIR/tmp_index_exec
	$WORKDIR/tmp_index_exec
	echo true > $WORKDIR/UPDATE_INDEX #update gui
	;;
-initialize_gui)
	grep -ciE "$AUDIO_FORMATS2" "$STORAGE_DIR/index_mymusic" > $WORKDIR/index_count_songs
	grep -ciE "\.pmu|\.m3u|\.pls" "$STORAGE_DIR/index_mymusic" > $WORKDIR/index_count_collections
#	cp "$STORAGE_DIR"/index_mymusic "$STORAGE_DIR"/index_mymusic.editor
	echo true > $WORKDIR/UPDATE_INDEX #update gui
	;;
-msg_quick_update)
	#the following delay is of course bad stuff, but a simple way to inform user what's happening.
	#all in all it's just the first run we get the sleep.
	[ ! -f $WORKDIR/gui_is_running ] && sleep 1
	[ ! -f $WORKDIR/gui_is_running ] && sleep 1
	[ ! -f $WORKDIR/gui_is_running ] && sleep 1
	[ ! -f $WORKDIR/gui_is_running ] && sleep 1
	echo 2 > $WORKDIR/maingui_notebook_page
	cp -f "$APPDIR/themes/$THEME/info.svg" $WORKDIR/albumart.jpg
	echo true > $WORKDIR/UPDATE_GUI
	#---
	$APPDIR/func_index -quick_update "$2"
	#reset gui
	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
	echo true > $WORKDIR/UPDATE_GUI
	;;
-quick_update)
	#if $2 --> specific source is asked to be scanned
	if [ "`grep "$STORAGE_DIR/pmu/" <<< "$2"`" ]; then #pMusic generated album list
		ARTIST="`basename "$2" | awk -F ' - ' '{print $1}'`"
		ALBUM="`basename "$2" | awk -F ' - ' '{print $2}' | sed -e 's/\.[^\.]*$//'`"
		echo "$2|$ARTIST||$ALBUM||||||||||$2|gtk-audio||||||" > $WORKDIR/index_tmp
	elif [ "$2" ]; then #other specified source
		find "$2" -printf "%p|%f|||||||0|||||%p|gtk-audio||||||\n" | grep -iE "$AUDIO_FORMATS2|\.pmu\||\.m3u\||\.pls\|" > $WORKDIR/index_tmp
	else
		echo -n > $WORKDIR/index_tmp
		while read I; do
			find -P "$I" -path '/initrd' -prune -o -printf "%p|%f|||||||0|||||%p|gtk-audio||||||\n" | grep -iE "$AUDIO_FORMATS2|\.pmu\||\.m3u\||\.pls\|" | grep -v "^${I}|" >> $WORKDIR/index_tmp
		done < "$STORAGE_DIR/index_directories"
	fi
	#change icon and remove rating for playlists
	grep -iE "\.pmu\||\.m3u\||\.pls\|" $WORKDIR/index_tmp | sed -e 's/|0|/||/g' -e 's/gtk-audio/gtk-audio_playlist/g' > $WORKDIR/index_tmp2
	( flock -e 200
		#build new db
		#remove double additions, but keep old entry if column 21 exists - that means full set of track info already exist in db
		#but for playlists we override existing (no extended info) since it will update icons from a pmusic-3 db
		cat $WORKDIR/index_tmp2 "$STORAGE_DIR/index_mymusic" $WORKDIR/index_tmp | sort -ust'|' -k1,1 | sort -rst'|' -k21,21 --output=$WORKDIR/index_tmp3 #sort by rating to place popular tracks first. This will be used by Overview - Rating
		#remove streamripper incomplete files
		grep -vF '/incomplete/' $WORKDIR/index_tmp3 > $WORKDIR/index_tmp4
		#write to db
		mv $WORKDIR/index_tmp4 "$STORAGE_DIR"/index_mymusic
	) 200>$WORKDIR/mymusic_db.lockfile
	;;

-update_index)
	[ ! "$(grep -F 'not_empty' <<< "$*")" ] && echo '' > "$STORAGE_DIR"/index_mymusic.editor #we start the gui with empty file for speed
	echo '' > $WORKDIR/index_count_songs
	echo '' > $WORKDIR/index_count_collections
	echo '' > $WORKDIR/index_splashtext
	echo 0 > $WORKDIR/index_splash
	echo false > $WORKDIR/UPDATE_INDEX
	[ "$(grep -F 'editor' <<< "$*")" ] && PAGE_NR=1 || PAGE_NR=0
	[ "$(grep -F 'use_meta' <<< "$*")" ] && CHK_USE_META_INDEX='<default>true</default>'
	[ "$(grep -F 'update_playlists' <<< "$*")" ] && CHK_UPDATE_PLAYLISTS_INDEX='<default>true</default>'
	[ "$(grep -F 'remove_non_existing' <<< "$*")" ] && CHK_REMOVE_NON_EXISTING_INDEX='<default>true</default>'
	
	$APPDIR/func_svg -heading "$(gettext 'My music DB')" > /dev/null
	template -third
	S='
<window title="pMusic - '$(gettext 'My Music DB')'" icon-name="pmusic">
 <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" wrap="false" space-expand="false" space-fill="false"><label>"<i><b>'$(gettext 'My Music')'</b> '$(gettext 'is a database of music on your system')'
<b><span color='"'#FF0000'"'>'$(gettext 'Note!')'</span></b> '$(gettext 'Edit DB will NOT affect your audio files (ie. meta-tags)')'</i>"</label></text>
	  <text space-expand="true" space-fill="true"><label>""</label></text>
     </hbox>
    </eventbox>
   </hbox>
  </vbox> 
 
  <notebook page="'$PAGE_NR'" tab-labels="'$(gettext 'Indexer')'|'$(gettext 'Editor')'" space-expand="true" space-fill="true">
   <vbox>
    <hbox>
     <pixmap icon_size="6"><input file stock="gtk-info"></input></pixmap>
     <text use-markup="true" space-expand="false" space-fill="false"><label>"'$(gettext 'During use, pMusic stores info of tracks like meta-tags, lyrics, albumart, ... If you want more info in place at once, you can scan your collection right now. Existing database is backed up in')' '"$STORAGE_DIR"'/index_mymusic.bak"</label></text>
     <text space-expand="true" space-fill="true"><label>""</label></text>
    </hbox>
    <vbox space-expand="true" space-fill="true">
     <frame '$(gettext 'Where to look for your music')'>
      <hbox space-expand="true" space-fill="true">
       <vbox space-expand="true" space-fill="true">
        <tree headers_visible="false" space-expand="true" space-fill="true">
         <label>a</label>
         <variable>SOURCE_SOURCE</variable>
         <input>cat "'$STORAGE_DIR'"/index_directories</input>
         <width>250</width><height>100</height>
         <action signal="button-release-event">enable:BUTTON_REMOVE</action>
        </tree>
       </vbox>
       <vbox space-expand="false" space-fill="false">
        <button space-expand="false" space-fill="false">
         <input file stock="gtk-add"></input>
         <action>. '$APPDIR'/func_index -add_to_indexlist</action>
         <action>refresh:SOURCE_SOURCE</action>
        </button>
        <button space-expand="false" space-fill="false">
         <variable>BUTTON_REMOVE</variable>
         <visible>disabled</visible>
         <input file stock="gtk-remove"></input>
         <action>. '$APPDIR'/func_index -remove_from_indexlist</action>
         <action>refresh:SOURCE_SOURCE</action>
        </button>
       </vbox>
      </hbox>
     </frame>
     <vbox space-expand="false" space-fill="false">
      <frame '$(gettext 'Options (much slower)')'>
       <checkbox>
        <label>'$(gettext 'Add meta-info to db')'</label>
        <variable>USE_META_INDEX</variable>
        '$CHK_USE_META_INDEX'
       </checkbox>
       <checkbox>
        <label>'$(gettext 'Remove entries in db pointing to non-existing files')'</label>
        <variable>REMOVE_NON_EXISTING_INDEX</variable>
        '$CHK_REMOVE_NON_EXISTING_INDEX'
       </checkbox>
       <checkbox>
        <label>'$(gettext 'Update sources in Album/Favorites lists')'</label>
        <variable>UPDATE_PLAYLISTS_INDEX</variable>
        '$CHK_UPDATE_PLAYLISTS_INDEX'
       </checkbox>
      </frame>
     </vbox> 
     <variable>VBOX1</variable>
    </vbox>
    <hbox space-expand="false" space-fill="false">
     <text use-markup="true"><label>"<b>'$(gettext 'Tracks')' : </b>"</label></text>
     <text><variable>COUNT_SONGS</variable><input file>'$WORKDIR'/index_count_songs</input></text>
     <text use-markup="true"><label>"<b>'$(gettext 'Collections')' : </b>"</label></text>
     <text><variable>COUNT_COLLECTIONS</variable><input file>'$WORKDIR'/index_count_collections</input></text>
    </hbox>
    <hbox space-expand="false" space-fill="false">
     <progressbar space-expand="true" space-fill="true">
      <variable>INDEX_PROGRESS</variable>
      <input>while [ "$I" != "100" ]; do I=`cat '$WORKDIR'/index_splash`; echo $I; cat '$WORKDIR'/index_splashtext;  sleep 1; done</input>
      <action type="exit">cancel</action>
     </progressbar>
     <button space-expand="false" space-fill="false">
      <input file stock="gtk-cancel"></input>
      <label>'$(gettext 'Cancel')'</label>
      <action>echo cancel > '$WORKDIR'/update_index_cancel</action>
      <action type="exit">cancel</action>
     </button>
     <button can-default="true" has-default="true" use-stock="true" space-expand="false" space-fill="false">
      <variable>BUTTON_START</variable>
      <input file stock="gtk-apply"></input>
      <label>'$(gettext 'Start indexing')'</label>
      <action>disable:VBOX1</action>
      <action>disable:BUTTON_START</action>
      <action>'$APPDIR'/func_index -build_index &</action>
     </button>
    </hbox>
   </vbox>
   
   
   <vbox>
    <hbox  homogeneous="true" space-expand="true" space-fill="true">
     <vbox space-expand="true" space-fill="true">
      <hbox space-expand="false" space-fill="false">
       <button space-expand="false" space-fill="false">
        <input file stock="gtk-go-down"></input>
        <label>'$(gettext 'Show DB')'</label>
        <action>cp "'$STORAGE_DIR'"/index_mymusic "'$STORAGE_DIR'"/index_mymusic.editor</action>
        <action>clear:DB</action>
        <action>refresh:DB</action>
       </button>
       <entry name="search" height-request="30" activates-default="true" is-focus="true" secondary-icon-stock="gtk-find" space-expand="true" space-fill="true">
        <variable>SEARCH_DB</variable>
        <default>"'$(gettext 'Search DB')'"</default>
        <action signal="activate">'$APPDIR'/func_index -search_db "$SEARCH_DB"</action>
        <action signal="activate">refresh:DB</action>
        <action signal="secondary-icon-release">'$APPDIR'/func_index -search_db "$SEARCH_DB"</action>
        <action signal="secondary-icon-release">refresh:DB</action>
        <action condition="command_is_true([[ `echo \"$SEARCH_DB\" | grep -F \"'$(gettext 'Search DB')'\"` ]] && echo true)" signal="enter-notify-event">clear:SEARCH_DB</action>
       </entry>

      </hbox>
      <vbox space-expand="true" space-fill="true">
       <table space-expand="true" space-fill="true">
        <label>"'$(gettext 'Command')'         |'$(gettext 'Artist / Filename')'                             |'$(gettext 'Title')'                             |'$(gettext 'Album')'                     |'$(gettext 'Nr')'  |'$(gettext 'Date')'     |'$(gettext 'Genre ')'     |'$(gettext 'Comment')'  |'$(gettext 'Rate')'|'$(gettext 'Format')'|'$(gettext 'Kb/s')'  |'$(gettext 'Length')'|'$(gettext 'Not in use')'|'$(gettext 'Path')'                                 |'$(gettext 'Icon')'|'$(gettext 'Disc-ID ')'musicbrainz.org|'$(gettext 'Artist-ID ')'musicbrainz.org|'$(gettext 'Lyrics source')'|'$(gettext 'Album-art source')'|'$(gettext 'Not in use')'|'$(gettext 'Timestamps')'                                                                                                                                     "</label>
        <variable>DB</variable>
        <input file>"'$STORAGE_DIR'/index_mymusic.editor"</input>
        <action>grep -F "$DB" "'$STORAGE_DIR'/index_mymusic" > '$WORKDIR'/tmp_index</action>
        '"$(template -first)"'
##      <action>pmusic -a "$DB" &</action>
       </table>    
      </vbox>
     </vbox>
    
     <vbox space-expand="true" space-fill="true">
      <hbox space-expand="false" space-fill="false">
       <button space-expand="false" space-fill="false">
        <label>'$(gettext 'Delete DB item')'</label>
        <input file stock="gtk-delete"></input>
        <action>delete_db</action>
        '"$(template -fourth)"'
       </button>
       <button space-expand="false" space-fill="false">
        <label>'$(gettext 'Save changes')'</label>
        <input file stock="gtk-save"></input>
        <action>save_db</action>
       </button>
      </hbox>

      <hbox space-expand="true" space-fill="true">
       <vbox scrollable="true">
        '"$(template -second)"'
       </vbox>
      </hbox>
     </vbox>
    </hbox>
   </vbox>

  </notebook>
  <checkbox visible="false" file-monitor="true" auto-refresh="true">
   <variable>UPDATE_INDEX</variable>
   <input file>'$WORKDIR'/UPDATE_INDEX</input>
   <action>if true clear:DB</action>
   <action>if true refresh:DB</action>
   <action>if true refresh:COUNT_SONGS</action>
   <action>if true refresh:COUNT_COLLECTIONS</action>
   <action>if true echo false > '$WORKDIR'/UPDATE_INDEX</action>
  </checkbox>
 </vbox>
 <action signal="show">'$APPDIR'/func_index -initialize_gui &</action>
 <action signal="delete-event">echo cancel > '$WORKDIR'/update_index_cancel</action>
</window>'

	echo "$S" | sed 's/##.*//' > $WORKDIR/xml_pmusic_mymusic #I use double hash (##) for comments. --> as #FF0000
	[ $TOOLTIPS = false ] && sed -i 's%tooltip-text%tooltipXXXtext%g' $WORKDIR/xml_pmusic_mymusic
	. $APPDIR/func -reset_gtk
	I=$IFS; IFS=""
	for STATEMENTS in  $($GTKDIALOG -f $WORKDIR/xml_pmusic_mymusic); do
		eval $STATEMENTS
	done
	IFS=$I
	echo 100 > $WORKDIR/index_splash #end loop
	if [ "$EXIT" = "cancel" ]; then
		for I in `ps -eo pid,command | grep update_index | awk '{print $1}'`; do kill -9 $I; done
		for I in `ps -eo pid,command | grep func_index | awk '{print $1}'`; do kill -9 $I; done
	fi
	;;
-add_to_indexlist)
	GET_OUTDIR="true"; TITLE="- $(gettext 'Index music directory')"; . $APPDIR/box_chooser
	if [ "$EXIT" = "OK" ]; then
		if [ ! -d "$CHOOSER" ]; then #dir not found
			TXT1="<b>$CHOOSER $(gettext 'not found')</b>"
			. $APPDIR/box_ok
		else
			echo "$CHOOSER" >> "$STORAGE_DIR/index_directories"
		fi
	fi
	;;
-remove_from_indexlist)
	grep -vx "$SOURCE_SOURCE" "$STORAGE_DIR/index_directories" > $WORKDIR/tmp
	mv -f $WORKDIR/tmp "$STORAGE_DIR/index_directories"
	;;
-build_index)
	[ $UTF8 = false ] && export LC_ALL=C
	rm $WORKDIR/update_index_cancel
	#calculate $TOTAL for progressbar
	#the different tasks get a 'weigth' by a multiplier to get a more correct progressbar.
	TOTAL=0
	[ ! -s $WORKDIR/index_count_songs ] && sleep 1 #wait for calculation
	[ $USE_META_INDEX = true ] && TOTAL=$((4*$(<$WORKDIR/index_count_songs)))
	[ $REMOVE_NON_EXISTING_INDEX = true ] && TOTAL=$(($TOTAL+$(wc -l < "$STORAGE_DIR/index_mymusic")))
	[ $UPDATE_PLAYLISTS_INDEX = true ] && TOTAL=$((20*($(wc -l <<< "$(find "$STORAGE_DIR/pmu" -type f -printf "%p\n")")+$(wc -l <<< "$(find "$STORAGE_DIR/favorite_lists" -type f -printf "%p\n")"))+$TOTAL))
	#---
	COUNT=0

	if [ $USE_META_INDEX = true ]; then #change name from filename to metatag artist - title
		echo "$(gettext 'Indexing files')" > $WORKDIR/index_splashtext
		echo -n > $WORKDIR/index_mymusic
		[ -s "$STORAGE_DIR/index_mymusic" ] && cp "$STORAGE_DIR/index_mymusic" $WORKDIR/index_mymusic #we don't want to work directly on index file since this process will take time and can be canceled
		#find both changed files and new added files
		echo -n > $WORKDIR/index_new
		while read I; do
			find "$I" -printf "%p\n" | grep -iE "$AUDIO_FORMATS|\.pmu$|\.m3u$|\.pls$" >> $WORKDIR/index_new
		done < "$STORAGE_DIR/index_directories"
		#check meta tag. file by file
		while read I; do
			$APPDIR/func_id3io "$I" -read $WORKDIR/index_mymusic
			#update progress bar
			PERCENT=$((($COUNT*100/$TOTAL)+1))
			echo $PERCENT > $WORKDIR/index_splash #update progressbar
			echo "$(gettext 'Indexing files'): $COUNT" > $WORKDIR/index_splashtext
			[ $PERCENT -lt 99 ] && COUNT=$(($COUNT+1))
			[ -s $WORKDIR/update_index_cancel ] && exit
		done < $WORKDIR/index_new
	else #only use filenames in add-list
		$APPDIR/func_index -quick_update
		cp "$STORAGE_DIR/index_mymusic" $WORKDIR/index_mymusic #you'll find similar line above, but here we need -quick_update to run _first_ 
	fi
	echo "$(gettext 'Improving syntax')" > $WORKDIR/index_splashtext
	#fix %20 and _ to spaces
	cut -d'|' -f1 $WORKDIR/index_mymusic > $WORKDIR/index_tmp0
	cut -d'|' -f2-8 $WORKDIR/index_mymusic > $WORKDIR/index_tmp1
	cut -d'|' -f9- $WORKDIR/index_mymusic > $WORKDIR/index_tmp
	cat $WORKDIR/index_tmp1 | tr '_' ' ' | sed 's/%20/ /g' > $WORKDIR/index_tmp2
	paste -d'|' $WORKDIR/index_tmp0 $WORKDIR/index_tmp2 $WORKDIR/index_tmp > $WORKDIR/index_mymusic
	#remove non-existing files
	if [ $REMOVE_NON_EXISTING_INDEX = true ]; then
		echo "$(gettext 'Checking for non-existing files')" > $WORKDIR/index_splashtext
		echo -n > $WORKDIR/index_tmp
		COUNT_NON=0
		while read I; do
			[ -f "`awk -F '|' '{print $1}' <<< "$I"`" ] && echo "$I" >> $WORKDIR/index_tmp
			#update progress bar
			COUNT_NON=$(($COUNT_NON+1))
			PERCENT=$((($COUNT*100/$TOTAL)+1))
			echo $PERCENT > $WORKDIR/index_splash #update progressbar
			echo "$(gettext 'Checking for non-existing files'): $COUNT_NON" > $WORKDIR/index_splashtext
			[ $PERCENT -lt 99 ] && COUNT=$(($COUNT+1))
			[ -s $WORKDIR/update_index_cancel ] && exit
		done < $WORKDIR/index_mymusic
		mv $WORKDIR/index_tmp $WORKDIR/index_mymusic
	fi
	#remove streamripper incomplete files
	grep -vF '/incomplete/' $WORKDIR/index_mymusic | sort -ust'|' -k1,1 | sort -rst'|' -k21,21 --output=$WORKDIR/index_mymusic2
	#reset
	( flock -e 200
		mv -f "$STORAGE_DIR"/index_mymusic "$STORAGE_DIR"/index_mymusic.bak
		mv $WORKDIR/index_mymusic2 "$STORAGE_DIR"/index_mymusic
	) 200>$WORKDIR/mymusic_db.lockfile 
	#update playlists
	if [ $UPDATE_PLAYLISTS_INDEX = true ]; then
		. $APPDIR/func_index -update_playlists
	fi
	#---
	echo 100 > $WORKDIR/index_splash
	$APPDIR/func -index_songs
	#cleanup
	sleep 1 #wait for progressbar to detect 'echo 100'
	rm $WORKDIR/index_*
	;;

-update_pmu) #we keep this in a standalone function to be used by -chek_playlist in ./func
	PMU="$2"
	echo -n > $WORKDIR/tmp_check_pmu
	while read I; do
		FILE_PATH="`cut -d'|' -f4 <<< "$I"`"
		#if path is valid, go to next
		if [ -s "$FILE_PATH" ]; then
			echo "$I" >> $WORKDIR/tmp_check_pmu
			continue
		fi
		#---
		LENGTH="`cut -d'|' -f2 <<< "$I"`"
		ARTIST="`cut -d'|' -f3 <<< "$I" | awk -F ' - ' '{print $1}'`"
		TITLE="`cut -d'|' -f3 <<< "$I" | awk -F ' - ' '{print $2}'`"
		if [ ! -f "$FILE_PATH" ]; then
			TITLE2="`echo "$TITLE" | awk -F "(" '{print $1}' | sed "s/ $//"`" #remove info in ()
			FILE_PATH_NEW="`cut -d'|' -f1-3 "$STORAGE_DIR/index_mymusic" | grep -iF "|${TITLE}|" | grep -Fi "|${ARTIST}|" | cut -d'|' -f1 | grep -iEm1 "$AUDIO_FORMATS"`"
			[ ! "$FILE_PATH_NEW" ] && FILE_PATH_NEW="`cut -d'|' -f1-3 "$STORAGE_DIR/index_mymusic" | grep -iF "${TITLE2}" | grep -Fi "${ARTIST}" | cut -d'|' -f1 | grep -iEm1 "$AUDIO_FORMATS"`"
			if [ -f "$FILE_PATH_NEW" ]; then
				FILE_PATH="$FILE_PATH_NEW"
				LENGTH="`grep -F "|${FILE_PATH_NEW}|" "$STORAGE_DIR/index_mymusic" | cut -d'|' -f12`"
				if [ ! "$LENGTH" ]; then
					ffmpeg -i "$FILE_PATH_NEW" > $WORKDIR/tmp_check_pmu_ffmpeg 2>&1
					LENGTH="`grep -wm1 "Duration:" $WORKDIR/tmp_check_pmu_ffmpeg | cut -d. -f1 | awk -F':' '{print $3":"$4}'`"
				fi
			else
				LENGTH='' #if no file found, length should be detected next time
				FILE_PATH=''
			fi
		fi
		TMP=`date +%s%N`
		echo "|$LENGTH|$ARTIST - $TITLE|$FILE_PATH|$TMP $FILE_PATH" >> $WORKDIR/tmp_check_pmu
	done < "$PMU"
	mv -f $WORKDIR/tmp_check_pmu "$PMU" #save
	;;
-update_pmd) #we keep this in a standalone function to be used by -chek_playlist in ./func
	PMD="$2"
	echo -n > $WORKDIR/tmp_check_pmd
	while read I; do
		FILE_PATH="`cut -d'|' -f14 <<< "$I"`"
		#if path is valid, go to next
		if [ -s "$FILE_PATH" ]; then
			echo "$I" >> $WORKDIR/tmp_check_pmd
			continue
		fi
		#---
		if [ ! -f "$FILE_PATH" ]; then
			FILE_NAME="`basename "$FILE_PATH"`" #first try the exact name
			FILE_PATH_NEW="`cut -d'|' -f14 "$STORAGE_DIR/index_mymusic" | grep "/${FILE_NAME}$"`"
			if [ ! "$FILE_PATH_NEW" ]; then #now try to remove content inside (), and case insensitive
				FILE_NAME="`basename "$FILE_PATH" | awk -F "(" '{print $1}' | sed "s/ $//"`"
				FILE_PATH_NEW="`cut -d'|' -f14 "$STORAGE_DIR/index_mymusic" | grep -iF "${FILE_NAME}"`"
			fi
			if [ "$FILE_PATH_NEW" ]; then
				grep -Fm1 "|${FILE_PATH_NEW}|" "$STORAGE_DIR/index_mymusic" >> $WORKDIR/tmp_check_pmd
			else
				echo "|${FILE_NAME}||||||||||||${FILE_PATH}|gtk-audio_missing" >> $WORKDIR/tmp_check_pmd
			fi
		fi
	done < "$PMD"
	mv -f $WORKDIR/tmp_check_pmd "$PMD" #save
	;;
-update_playlists)
	#PMU
	find "$STORAGE_DIR/pmu" -type f -printf "%p\n" > $WORKDIR/tmp_check_playlist
	echo "$(gettext 'Update Album lists')" > $WORKDIR/index_splashtext
	COUNT_PMU=0
	while read PMU; do   
		$0 -update_pmu "$PMU"
		#update progress bar
		COUNT_PMU=$(($COUNT_PMU+1))
		PERCENT=$((($COUNT*100/$TOTAL)+1))
		echo $PERCENT > $WORKDIR/index_splash #update progressbar
		echo "$(gettext 'Update Album lists'): $COUNT_PMU" > $WORKDIR/index_splashtext
		[ $PERCENT -lt 99 ] && COUNT=$(($COUNT+20))
		[ -s $WORKDIR/update_index_cancel ] && exit
	done < $WORKDIR/tmp_check_playlist

	#PMD
	find "$STORAGE_DIR/favorite_lists" -type f -printf "%p\n" > $WORKDIR/tmp_check_playlist
	echo "$(gettext 'Update Favorites lists')" > $WORKDIR/index_splashtext
	COUNT_PMD=0
	while read PMD; do  
		$0 -update_pmd "$PMD"
		#update progress bar
		COUNT_PMD=$(($COUNT_PMD+1))
		PERCENT=$((($COUNT*100/$TOTAL)+1))
		echo $PERCENT > $WORKDIR/index_splash #update progressbar
		echo "$(gettext 'Update Favorites lists'): $COUNT_PMD" > $WORKDIR/index_splashtext
		[ $PERCENT -lt 99 ] && COUNT=$(($COUNT+1))
		[ -s $WORKDIR/update_index_cancel ] && exit
	done < $WORKDIR/tmp_check_playlist

	;;
esac

