#!/bin/bash
#Pmusic
#Copyright 2008,2009,2010,2011,2012,2013,2014
#Sigmund Berglund

export TEXTDOMAIN=pmusic
. $APPDIR/func -reset_gtk
$APPDIR/func -kill_browser_id3 #kill ongoing process
export ID3_GENRES=`awk -F "(" '{print "<item>"$1"("$2"</item>"}' $APPDIR/txt_id3genre` #build id3 genres

echo "$(gettext "This will edit the meta information of ALL supported
tracks in the chosen list. Untouched tags will NOT
be removed. This means you can add one of the tags
to all your files without removing the others.

For advanced tagging you can use shell commands
instead of static text in the fields. This is very
useful to track-titles which almost never will be
equal to another one.
Some examples:

Filename is 'artist - title.mp3'.
Command to grab title will be:")" > $WORKDIR/masstagger_info
echo -e "<span fgcolor='"'darkgreen'"'><i>exe:echo 'FILENAME' | awk -F ' - ' '{print \\\$2}'</i></span>\n" >> $WORKDIR/masstagger_info

echo "$(gettext "Album might be the name of the directory:")" >> $WORKDIR/masstagger_info
echo -e "<span fgcolor='"'darkgreen'"'><i>exe:echo 'DIRNAME'</i></span>\n" >> $WORKDIR/masstagger_info

echo "$(gettext "Track-title in an e-book could be named like this:")" >> $WORKDIR/masstagger_info
echo -e "<span fgcolor='"'darkgreen'"'><i>exe:echo 'Mybook chapter '"'\$(printf "%02d" COUNT)'"</i></span>\n" >> $WORKDIR/masstagger_info

echo "$(gettext "To clear a chosen tag, use the builtin command:")" >> $WORKDIR/masstagger_info
echo -e "<span fgcolor='"'darkgreen'"'><i>exe:CLEAR</i></span>\n" >> $WORKDIR/masstagger_info

echo "$(gettext "And then the rules:
- Line must start with exe:
- Builtin variables are FILENAME, DIRNAME and COUNT
- Builtin command is CLEAR
- Never use \"
- Place a \\ in front of \$")" >> $WORKDIR/masstagger_info

set_albumart (){
	GET_OUTDIR=false; TITLE="- $(gettext 'Define albumart sourcefile')"; . $APPDIR/box_chooser
	if [ "$EXIT" = "OK" ]; then
		if [ -f "$CHOOSER" ] && [ "`grep -iE "\.jpg$|\.png$|\.gif$" <<< "$CHOOSER"`" ]; then
			rm $WORKDIR/tmp_masstagger_albumart.jpg
			cp "$CHOOSER" $WORKDIR/tmp_masstagger_albumart.jpg
		else
			TXT1="<b>$(gettext 'No valid image file')</b> (jpg/png/gif)"
			TXT2="$CHOOSER"
			. $APPDIR/box_ok
		fi
	fi
}

fetch_dir (){
	GET_OUTDIR=false
	TITLE="- $(gettext 'Define albumart sourcefile')"
	XML_CHOOSER='
	<hseparator></hseparator>
	<checkbox>
	 <variable>CHK_RECURSIVE</variable>
	 <label>"'$(gettext 'Add recursively (also add files from sub-directories)')'"</label>
	</checkbox>
	'
	. $APPDIR/box_chooser
	if [ "$(grep -F directory <<< $(file "$CHOOSER"))" ]; then
		if [ $CHK_RECURSIVE = true ]; then
			find "$CHOOSER" | grep -E "$AUDIO_FORMATS" >> $WORKDIR/id3tagger
		else
			find "$CHOOSER" -mindepth 1 -maxdepth 1 -printf "%p\n" | grep -E "$AUDIO_FORMATS" >> $WORKDIR/id3tagger
		fi
	else
		echo "$CHOOSER" >> $WORKDIR/id3tagger
	fi
}

export -f set_albumart fetch_dir

cp $WORKDIR/albumart.jpg $WORKDIR/tmp_masstagger_albumart.jpg
$APPDIR/func_svg -heading "$(gettext 'Mass tagger')"

echo '
<window title="pMusic - '$(gettext 'Mass tagger')'" icon-name="pmusic" default_width="470" default_height="400">
<vbox space-expand="true" space-fill="true">
 <vbox space-expand="false" space-fill="false">
  <hbox spacing="0" height="75" scrollable="true" space-expand="true" space-fill="true" vscrollbar-policy="2" hscrollbar-policy="2">
   <eventbox name="svgheading" space-expand="true" space-fill="true">
    <hbox space-expand="true" space-fill="true">
     <text width-request="20" space-expand="false" space-fill="false"><label>""</label></text>
     <text ypad="45" use-markup="true" space-expand="false" space-fill="false"><label>"<i>'$(gettext 'Tag several files in one click')'</i>"</label></text>
     <text space-expand="true" space-fill="true"><label>""</label></text>
   </hbox>
   </eventbox>
  </hbox>
 </vbox>

 <hbox space-expand="true" space-fill="true">
  <vbox space-expand="true" space-fill="true">
   <frame '$(gettext 'Tags')'>
    <hbox>
     <text width-request="100" use-markup="true"><label>"<b>'$(gettext 'Artist')'</b>"</label></text>
     <entry primary-icon-stock="gtk-clear" >
      <variable>ARTIST</variable><default>"'$ARTIST'"</default>
      <action signal="primary-icon-release">clear:ARTIST</action>
     </entry>
    </hbox>
    <hbox>
     <text width-request="100" use-markup="true"><label>"<b>'$(gettext 'Title')'</b>"</label></text>
     <entry primary-icon-stock="gtk-clear" >
      <variable>TITLE</variable>
      <action signal="primary-icon-release">clear:TITLE</action>
     </entry>
    </hbox>
    <hbox>
     <text width-request="100" use-markup="true"><label>"<b>'$(gettext 'Album')'</b>"</label></text>
     <entry primary-icon-stock="gtk-clear" >
      <variable>ALBUM</variable>
      <default>"'$ALBUM'"</default>
      <action signal="primary-icon-release">clear:ALBUM</action>
     </entry>
    </hbox>
    <hbox>
     <text width-request="100" use-markup="true"><label>"<b>'$(gettext 'Year')'</b>"</label></text>
     <entry primary-icon-stock="gtk-clear">
      <variable>YEAR</variable>
      <default>"'$YEAR'"</default>
      <action signal="primary-icon-release">clear:YEAR</action>
     </entry>
    </hbox>
    <hbox spacing="0">
     <text width-request="105" use-markup="true"><label>"<b>'$(gettext 'Track nr')'</b>"</label></text>
     <entry primary-icon-stock="gtk-clear" >
      <variable>TRACK</variable>
      <input file>'$WORKDIR'/tmp_id3tagger_track</input>
      <action signal="primary-icon-release">echo "" > '$WORKDIR'/tmp_id3tagger_track</action>
      <action signal="primary-icon-release">refresh:TRACK</action>
     </entry>
     <button width-request="27" height-request="27">
      <input file stock="gtk-go-back"></input>
      <action>echo "exe:printf \"%01d\" COUNT" > '$WORKDIR'/tmp_id3tagger_track</action>
      <action>refresh:TRACK</action>
      <action>rm '$WORKDIR'/tmp_id3tagger_track</action>
     </button>
    </hbox>
    <hbox>
     <text width-request="100" use-markup="true"><label>"<b>'$(gettext 'Comment')'</b>"</label></text>
     <entry primary-icon-stock="gtk-clear">
      <variable>COMMENT</variable>
      <action signal="primary-icon-release">clear:COMMENT</action>
     </entry>
    </hbox>
    <hbox>
     <text space-expand="false" space-fill="false" use-markup="true"><label>"<b>'$(gettext 'Genre')'</b>"</label></text>
     <hbox space-expand="true" space-fill="true">
      <text><label>""</label></text>
     </hbox>
     <comboboxentry><variable>GENRE</variable><default>"'$GENRE'"</default>'$ID3_GENRES'</comboboxentry>
    </hbox>
    <text><label>""</label></text>
    <hseparator></hseparator>
    <text><label>""</label></text>
    <hbox>
     <pixmap space-expand="false" space-fill="false">
      <width>100</width>
      <height>100</height>
      <variable>PIC_ALBUMART</variable>
      <input file>'$WORKDIR'/tmp_masstagger_albumart.jpg</input>
      <sensitive>false</sensitive>
     </pixmap>
     <text space-expand="false" space-fill="false" width-request="10"><label>""</label></text>
     <vbox>
      <checkbox>
       <variable>ALBUMART</variable>
       <label>'$(gettext 'Embed image to ALL files')'</label>
       <action>if true enable:PIC_ALBUMART</action>
       <action>if true enable:SET_ALBUMART</action>
       <action>if false disable:PIC_ALBUMART</action>
       <action>if false disable:SET_ALBUMART</action>
      </checkbox>
      <text space-expand="true" space-fill="true"><label>""</label></text>
      <hbox space-expand="false" space-fill="false">
      <button space-expand="false" space-fill="false">
       <variable>SET_ALBUMART</variable>
       <input file stock="gtk-open"></input>
       <label>'$(gettext 'Another image')'</label>
       <sensitive>false</sensitive>
       <action>set_albumart</action>
       <action>refresh:PIC_ALBUMART</action>
      </button>
      <text space-expand="true" space-fill="true"><label>""</label></text>
      </hbox>
     </vbox>
     <text space-expand="true" space-fill="true"><label>""</label></text>
    </hbox>
   </frame>
   <hbox space-expand="false" space-fill="false">
    <hbox space-expand="true" space-fill="true">
     <text><label>""</label></text>
    </hbox>
    <button space-expand="false" space-fill="false">
     <label>'$(gettext 'Clear tags')'</label>
     <input file stock="gtk-clear"></input>
     <action>save:TAG_FILES</action>
     <action type="exit">clear_tag</action>
    </button>
    <button space-expand="false" space-fill="false">
     <label>'$(gettext 'Save tags')'</label>
     <input file stock="gtk-save"></input>
     <action>save:TAG_FILES</action>
     <action type="exit">save</action>
    </button>
   </hbox>
  </vbox>
  <vbox space-expand="true" space-fill="true">
   <notebook labels="  '$(gettext 'Files')'  |  '$(gettext 'Info')'  ">
    <vbox space-expand="true" space-fill="true">
     <text height-request="1" space-expand="false" space-fill="false"><label>""</label></text>
     <hbox space-expand="false" space-fill="false">
      <text width-request="0" space-expand="false" space-fill="false"><label>""</label></text>
      <button space-expand="false" space-fill="false">
       <input file stock="gtk-open"></input>
       <action>fetch_dir</action>
       <action>refresh:TAG_FILES</action>
       <action>refresh:ID3_STATUSBAR</action>
      </button>
      <button space-expand="false" space-fill="false">
       <label>'$(gettext 'Fetch PlayQueue')'</label>
       <action>cut -d"|" -f4 '$WORKDIR'/playlist >> '$WORKDIR'/id3tagger</action>
       <action>refresh:TAG_FILES</action>
       <action>refresh:ID3_STATUSBAR</action>
      </button>
      <button space-expand="false" space-fill="false">
       <label>'$(gettext 'Fetch Sourcelist')'</label>
       <action>cut -d"|" -f14 '$WORKDIR'/sourcelist | grep -E "'$AUDIO_FORMATS'" >> '$WORKDIR'/id3tagger</action>
       <action>refresh:TAG_FILES</action>
       <action>refresh:ID3_STATUSBAR</action>
      </button>
      <button space-expand="false" space-fill="false">
       <label>'$(gettext 'Clear list')'</label> 
       <input file stock="gtk-clear"></input>
       <action>echo -n > '$WORKDIR'/id3tagger</action>
       <action>refresh:TAG_FILES</action>
       <action>refresh:ID3_STATUSBAR</action>
      </button>
      <text width-request="0" space-expand="false" space-fill="false"><label>""</label></text>
     </hbox>
     <hbox space-expand="true" space-fill="true">
      <tree stock-id="gtk-audio" file-monitor="true" auto-refresh="true" headers-visible="false" space-expand="true" space-fill="true">
       <variable>TAG_FILES</variable>
       <input file>'$WORKDIR'/id3tagger</input>
       <output file>'$WORKDIR'/id3tagger</output>
      </tree>
     </hbox>
    </vbox>
    <vbox scrollable="true">
     <text height-request="5" space-expand="false" space-fill="false"><label>""</label></text>
     <hbox space-expand="false" space-fill="false">
      <vbox space-expand="false" space-fill="false">
       <pixmap icon_size="6" space-expand="false" space-fill="false"><input file stock="gtk-info"></input></pixmap>
       <text space-expand="true" space-fill="true"><label>""</label></text>
      </vbox>
      <text use-markup="true" selectable="true" can-focus="false" space-expand="false" space-fill="false"><input file>'$WORKDIR'/masstagger_info</input></text>
      <text space-expand="true" space-fill="true"><label>""</label></text>
     </hbox>
    </vbox>
   </notebook>
   <vbox space-expand="false" space-fill="false">
    <statusbar space-expand="true" space-fill="true">
     <variable>ID3_STATUSBAR</variable>
     <input>echo " $(cat '$WORKDIR'/id3tagger | wc -l) '$(gettext 'files added to list')'"</input>
    </statusbar>
   </vbox>
  </vbox>
 </hbox>
</vbox>
</window>' > $WORKDIR/xml_pmusic_id3tagger
[ $TOOLTIPS = false ] && sed -i 's%tooltip-text%tooltipXXXtext%g' $WORKDIR/xml_pmusic_id3tagger #deactivate tooltips
IFS=""
for STATEMENTS in $($GTKDIALOG -f $WORKDIR/xml_pmusic_id3tagger); do
	eval $STATEMENTS
done

if [ "$EXIT" = "Cancel" ] || [ "$EXIT" = "abort" ] || [ ! "$EXIT" ]; then exit; fi
RETVAL="$EXIT"
#Message: Do you really want to clear all tags
if [ "$EXIT" = "clear_tag" ]; then
	FRAME="$(gettext 'Clear tags')"; IMG="question"
	TXT1="$(gettext 'Do you really want to clear the tags for ALL files in the list?
Be aware that this also removes any embedded albumart.')"
	. $APPDIR/box_yesno
	[ $EXIT != "yes" ] && exit
fi

#show splash
echo "$(gettext 'Tagging files')..." > $WORKDIR/splashtext
$APPDIR/box_splash progress &

echo '#!/bin/sh' > $WORKDIR/exec_tagging2
COUNT=0
TOTAL=`grep -c ^ $WORKDIR/id3tagger`
echo -n > $WORKDIR/tmp_id3db
while read FILE; do
	[ ! -s "$FILE" ] && continue
	#update progressbar
	echo "50 * $COUNT / $TOTAL" | bc > $WORKDIR/splash 
	COUNT=$(($COUNT+1))
	#Variables used in exe: ... COUNT might also be used
	FILENAME="`basename "$FILE" | sed -e 's/\.[^\.]*$//' -e "s/'/'\\\\\\\\\\\\\''/g" -e 's/&/\\\&/g'`" #'
	TMP="`dirname "$FILE"`"
	DIRNAME="`basename "$TMP"`"
	#---
	. $APPDIR/func_id3io "$FILE" -read
	[ "$ARTIST" ] && ID3_ARTIST="$ARTIST"
	[ "$TITLE" ] && ID3_TITLE="$TITLE"
	[ "$ALBUM" ] && ID3_ALBUM="$ALBUM"
	[ "$YEAR" ] && ID3_YEAR="$YEAR"
	[ "$TRACK" ] && ID3_TRACK="$TRACK"
	[ "$GENRE" ] && ID3_GENRE="$GENRE"
	[ "$COMMENT" ] && ID3_COMMENT="$COMMENT"
	if [ "`echo "$ARTIST" | grep "^exe:"`" ]; then #acting on source variable would stop dynamic exe: updates
		if [ "`echo "$ARTIST" | grep -F CLEAR`" ]; then
			ID3_ARTIST=''
		else
			echo "$ARTIST" | cut -d: -f2- | sed -e "s%FILENAME%$FILENAME%g" -e "s%COUNT%$COUNT%g" -e "s%DIRNAME%$DIRNAME%g" > $WORKDIR/exec_tagging
			chmod 722 $WORKDIR/exec_tagging
			ID3_ARTIST="`$WORKDIR/exec_tagging`"
		fi
	fi
	if [ "`echo "$TITLE" | grep "^exe:"`" ]; then
		if [ "`echo "$TITLE" | grep -F CLEAR`" ]; then
			ID3_TITLE=''
		else
			echo "$TITLE" | cut -d: -f2- | sed -e "s%FILENAME%$FILENAME%g" -e "s%COUNT%$COUNT%g" -e "s%DIRNAME%$DIRNAME%g"> $WORKDIR/exec_tagging
			chmod 722 $WORKDIR/exec_tagging
			ID3_TITLE="`$WORKDIR/exec_tagging`"
		fi
	fi
	if [ "`echo "$ALBUM" | grep "^exe:"`" ]; then
		if [ "`echo "$ALBUM" | grep -F CLEAR`" ]; then
			ID3_ALBUM=''
		else
			echo "$ALBUM" | cut -d: -f2- | sed -e "s%FILENAME%$FILENAME%g" -e "s%COUNT%$COUNT%g" -e "s%DIRNAME%$DIRNAME%g"> $WORKDIR/exec_tagging
			chmod 722 $WORKDIR/exec_tagging
			ID3_ALBUM="`$WORKDIR/exec_tagging`"
		fi
	fi
	if [ "`echo "$YEAR" | grep "^exe:"`" ]; then
		if [ "`echo "$YEAR" | grep -F CLEAR`" ]; then
			ID3_YEAR=''
		else
			echo "$YEAR" | cut -d: -f2- | sed -e "s%FILENAME%$FILENAME%g" -e "s%COUNT%$COUNT%g" -e "s%DIRNAME%$DIRNAME%g"> $WORKDIR/exec_tagging
			chmod 722 $WORKDIR/exec_tagging
			ID3_YEAR="`$WORKDIR/exec_tagging`"
		fi
	fi
	if [ "`echo "$TRACK" | grep "^exe:"`" ]; then
		if [ "`echo "$TRACK" | grep -F CLEAR`" ]; then
			ID3_TRACK=''
		else
			echo "$TRACK" | cut -d: -f2- | sed -e "s%FILENAME%$FILENAME%g" -e "s%COUNT%$COUNT%g" -e "s%DIRNAME%$DIRNAME%g"> $WORKDIR/exec_tagging
			chmod 722 $WORKDIR/exec_tagging
			ID3_TRACK="`$WORKDIR/exec_tagging`"
		fi
	fi
	if [ "`echo "$GENRE" | grep "^exe:"`" ]; then
		if [ "`echo "$GENRE" | grep -F CLEAR`" ]; then
			ID3_GENRE=''
		else
			echo "$GENRE" | cut -d: -f2- | sed -e "s%FILENAME%$FILENAME%g" -e "s%COUNT%$COUNT%g" -e "s%DIRNAME%$DIRNAME%g"> $WORKDIR/exec_tagging
			chmod 722 $WORKDIR/exec_tagging
			ID3_GENRE="`$WORKDIR/exec_tagging`"
		fi
	else
		#convert genre number to something human readable. See $APPDIR/txt_id3genre
		TMP="`echo "$ID3_GENRE" | cut -d'(' -f2 | cut -d')' -f1`"
		if [ "$TMP" -lt "300" ]; then #it contains a number
			[ $TMP != 0 ] && TMP="`echo "$TMP" | sed -e 's/^00//' -e 's/^0//'`"
			ID3_GENRE="`grep -Fm1 "(${TMP})" $APPDIR/txt_id3genre | cut -d'(' -f1`"
		fi
	fi
	if [ "`echo "$COMMENT" | grep "^exe:"`" ]; then
		if [ "`echo "$COMMENT" | grep -F CLEAR`" ]; then
			ID3_COMMENT=''
		else
			echo "$COMMENT" | cut -d: -f2- | sed -e "s%FILENAME%$FILENAME%g" -e "s%COUNT%$COUNT%g" -e "s%DIRNAME%$DIRNAME%g"> $WORKDIR/exec_tagging
			chmod 722 $WORKDIR/exec_tagging
			ID3_COMMENT="`$WORKDIR/exec_tagging`"
		fi
	fi

	case $RETVAL in
		save)
			EXTENSION="`basename "$FILE" | sed -e "s/^.*\.//g"`"
			[ "$ALBUMART" = true ] && ID3_ALBUMART="-i $WORKDIR/tmp_masstagger_albumart.jpg" 
			echo "ffmpeg -i \"$FILE\" $ID3_ALBUMART -acodec copy -id3v2_version 3 -metadata title=\"$ID3_TITLE\" -metadata artist=\"$ID3_ARTIST\" -metadata album=\"$ID3_ALBUM\" -metadata year=\"$ID3_YEAR\" -metadata track=\"$ID3_TRACK\" -metadata comment=\"$ID3_COMMENT\" -metadata genre=\"$ID3_GENRE\" -y $WORKDIR/tmp_ffmpeg_copy.$EXTENSION" >> $WORKDIR/exec_tagging2
			echo "mv -f $WORKDIR/tmp_ffmpeg_copy.$EXTENSION \"$FILE\"" >> $WORKDIR/exec_tagging2
			echo "grep -F \"$FILE\" \"$STORAGE_DIR/index_mymusic\" | awk -F'|' -v VAR1=\"$ID3_ARTIST\" -v VAR2=\"$ID3_TITLE\" -v VAR3=\"$ID3_ALBUM\" -v VAR4=\"$ID3_TRACK\" -v VAR5=\"$ID3_YEAR\" -v VAR6=\"$ID3_GENRE\" -v VAR7=\"$ID3_COMMENT\" '{print \$1 \"|\" VAR1 \"|\" VAR2 \"|\" VAR3 \"|\" VAR4 \"|\" VAR5 \"|\" VAR6 \"|\" VAR7 \"|\" \$9 \"|\" \$10 \"|\" \$11 \"|\" \$12 \"|\" \$13 \"|\" \$14 \"|\" \$15 \"|\" \$16 \"|\" \$17 \"|\" VAR1 \"|\" \$19 \"|\" \$20 \"|\" \$21}' >> $WORKDIR/tmp_id3db" >> $WORKDIR/exec_tagging2
			;;
		clear_tag)
			EXTENSION="`basename "$FILE" | sed -e "s/^.*\.//g"`"
			FILENAME="`basename "$FILE"`"
			echo "ffmpeg -i \"$FILE\" -acodec copy -id3v2_version 3 -metadata title='' -metadata artist='' -metadata album='' -metadata year='' -metadata track='' -metadata comment='' -metadata genre='' -vn -y $WORKDIR/tmp_ffmpeg_copy.$EXTENSION" >> $WORKDIR/exec_tagging2
			echo "mv -f $WORKDIR/tmp_ffmpeg_copy.$EXTENSION \"$FILE\"" >> $WORKDIR/exec_tagging2
			echo "grep -F \"$FILE\" \"$STORAGE_DIR/index_mymusic\" | awk -F'|' '{print \$1 \"|$FILENAME|||||||\" \$9 \"|\" \$10 \"|\" \$11 \"|\" \$12 \"|\" \$13 \"|\" \$14 \"|\" \$15 \"|\" \$16 \"|\" \$17 \"|\" VAR1 \"||\" \$20 \"|\" \$21}' >> $WORKDIR/tmp_id3db" >> $WORKDIR/exec_tagging2
			;;
	esac
	echo "echo \"(50 * $COUNT / $TOTAL ) + 50\" | bc > $WORKDIR/splash" >> $WORKDIR/exec_tagging2
	echo "COUNT=$(($COUNT+1))" >> $WORKDIR/exec_tagging2

done <<< "$(cut -d'|' -f3 $WORKDIR/id3tagger)"
chmod 722 $WORKDIR/exec_tagging2
#update db
( flock -e 200
	$WORKDIR/exec_tagging2
	cat $WORKDIR/tmp_id3db "$STORAGE_DIR/index_mymusic" | sort -ust'|' -k1,1 | sort -rst'|' -k21,21 --output=$WORKDIR/tmp_id3
	mv $WORKDIR/tmp_id3 "$STORAGE_DIR/index_mymusic"
) 200>$WORKDIR/mymusic_db.lockfile 
#---
echo 100 > $WORKDIR/splash
echo -n > $WORKDIR/id3tagger
