#!/bin/bash
#this tool reads/writes meta-tags used by pMusic.
#Uses ffmpeg
#Genre is returning number and not the genre-name. This because of speed.  
FILE="$1"
[ $UTF8 = false ] && export LC_ALL=C #for grep speed

#read $3
if [ -f "$3" ]; then #$3 is used from func_index
	SUFFIX=func_index
	DB="$3" #let func_index use a temporary index so that pMusic can work normally during indexing, and because the user might want to cancel the indexing.
else
	SUFFIX="$(date +%s%N)" #unique suffix for every instance of func_id3io, rather than using MYPID from func_trackinfo which gives same suffix for different instances. --> SUFFIX=$3 #PID_GUI
	DB="$STORAGE_DIR/index_mymusic"
fi

update_lists () {
	#playlist
	if [ "$OLD_PLAYLIST_NAME" ]; then
		echo '( flock -e 201' > $WORKDIR/tmp_exec
		echo 'OLD_PLAYLIST_NAME="`grep -F "$FILE" $WORKDIR/playlist | cut -d'|' -f3`"' >> $WORKDIR/tmp_exec
		echo "sed -i 's/$OLD_PLAYLIST_NAME/$NEW_PLAYLIST_NAME/' $WORKDIR/playlist" >> $WORKDIR/tmp_exec
		echo ') 201> $WORKDIR/playlist.lockfile' >> $WORKDIR/tmp_exec
		echo 'echo true > $WORKDIR/UPDATE_GUI' >> $WORKDIR/tmp_exec
		sed -i 's/\&/\\\&/g' $WORKDIR/tmp_exec
		chmod 722 $WORKDIR/tmp_exec
		$WORKDIR/tmp_exec &
	fi
	#sourcelist
	OLD_ARTIST="`grep -F "$FILE" $WORKDIR/sourcelist | cut -d'|' -f2`"
	OLD_TITLE="`grep -F "$FILE" $WORKDIR/sourcelist | cut -d'|' -f3`"
	if [ "$OLD_ARTIST" ] || [ "$OLD_TITLE" ]; then
		SEARCH="$(tail -n1 "$STORAGE_DIR/index_history" | cut -d'|' -f3 | cut -c 5-)"
		if [ "`grep -F 'pMusic: Favorites' <<< "$SEARCH"`" ]; then 
			$APPDIR/func_favorites -show_favorites
		elif [ "`grep -F 'pMusic:' <<< "$SEARCH"`" ]; then #do nothing
			echo
		else
			$APPDIR/func -search_sources "$SEARCH" &
		fi
	fi
}
export -f update_lists




case "$2" in
-read*)
	[ ! -f "$FILE" ] && break
	[ ! -s "$DB" ] && break #in case file-lock restricts access
	INFO="`grep -Fm1 "${FILE}|" "$DB"`"
	FF_LENGTH="`cut -d'|' -f12 <<< "$INFO"`" #length is critical for general work, so we always check this
	#skip complete read if info already in index
	if [ "$FF_LENGTH" ]; then 
		FF_BITRATE="`cut -d'|' -f11 <<< "$INFO"`"
		FF_FORMAT="`cut -d'|' -f10 <<< "$INFO"`"
		ID3_ARTIST="`cut -d'|' -f2 <<< "$INFO"`"
		ID3_TITLE="`cut -d'|' -f3 <<< "$INFO"`"
		ID3_ALBUM="`cut -d'|' -f4 <<< "$INFO"`"
		ID3_TRACK="`cut -d'|' -f5 <<< "$INFO"`"
		ID3_YEAR="`cut -d'|' -f6 <<< "$INFO"`"
		ID3_GENRE="`cut -d'|' -f7 <<< "$INFO"`"
		ID3_COMMENT="`cut -d'|' -f8 <<< "$INFO"`"
		SKIP_DB_WRITE=true
	else
		if [ "`echo "$FILE" | grep -iE "\.kar$|\.mid$"`" ]; then
			TMP="`timidity -OuM8 -o $WORKDIR/tmp_midi.au "$SOURCE" | grep -F 'Playing time' | cut -d'~' -f2 | cut -d' ' -f1`" #seconds
			FF_LENGTH=`$APPDIR/func -sec2time $TMP`
			FF_FORMAT="midi"
			ID3_ARTIST="`basename "$FILE" | awk -F ' - ' '{print $1}' | sed -e 's/\.[^\.]*$//'`"
			ID3_TITLE="`basename "$FILE" | awk -F ' - ' '{print $2}' | sed -e 's/\.[^\.]*$//'`"
		else
			ffmpeg -i "$FILE" > $WORKDIR/tmp_id3ffmpeg$SUFFIX 2>&1
			FF_LENGTH="`grep -wm1 "Duration:" $WORKDIR/tmp_id3ffmpeg$SUFFIX | cut -d. -f1 | awk -F':' '{print $3":"$4}'`"
			FF_BITRATE="`grep -wm1 "Audio:" $WORKDIR/tmp_id3ffmpeg$SUFFIX | cut -d: -f4 | awk -F' ' '{print $6}' | tr ',' ' '`"
			FF_FORMAT="`grep -wm1 "Audio:" $WORKDIR/tmp_id3ffmpeg$SUFFIX | cut -d: -f4 | awk -F' ' '{print $1}' | tr ',' ' '`"
			ID3_TITLE="`grep -wim1 "^    title" $WORKDIR/tmp_id3ffmpeg$SUFFIX | cut -d: -f2- | cut -d' ' -f2-`"
			ID3_ARTIST="`grep -wim1 "^    artist" $WORKDIR/tmp_id3ffmpeg$SUFFIX | cut -d: -f2- | cut -d' ' -f2-`"
			ID3_ALBUM="`grep -wim1 "^    album" $WORKDIR/tmp_id3ffmpeg$SUFFIX | cut -d: -f2- | cut -d' ' -f2-`"
			ID3_YEAR="`grep -wim1 "^    year" $WORKDIR/tmp_id3ffmpeg$SUFFIX | cut -d: -f2- | cut -d' ' -f2-`"
			ID3_COMMENT="`grep -wim1 "^    comment" $WORKDIR/tmp_id3ffmpeg$SUFFIX | cut -d: -f2- | cut -d' ' -f2-`"
			ID3_TRACK="`grep -wim1 "^    track" $WORKDIR/tmp_id3ffmpeg$SUFFIX | cut -d: -f2- | cut -d' ' -f2-`"
			ID3_GENRE="`grep -wim1 "^    genre" $WORKDIR/tmp_id3ffmpeg$SUFFIX | cut -d: -f2- | cut -d' ' -f2-`"
			ID3_ALBUMART="`grep -wm1 "Video:" $WORKDIR/tmp_id3ffmpeg$SUFFIX | cut -d: -f4 | awk -F' ' '{print $1}' | tr ',' ' '`"
			rm $WORKDIR/tmp_id3ffmpeg$SUFFIX
		fi
	fi
	#rating
	RATING="`cut -d'|' -f9 <<< "$INFO"`"
	RATING_TIMESTAMPS="`cut -d'|' -f21 <<< "$INFO"`"
	#set icon
	[ "`grep -iE "\.pmu$|\.m3u$|\.pls$" <<< "$FILE"`" ] && ICON='gtk-audio_playlist' || ICON='gtk-audio'
	#---
	[ ! "$INPUT_MB_DISC_ID" ] && MB_DISC_ID="`echo "$INFO" | cut -d'|' -f16`" #$INPUT_MB_DISC_ID - overwrite existing with specified. See trackinfo - album-tag
	MB_ARTIST_ID="`cut -d'|' -f17 <<< "$INFO"`"
	URL_LYRICS="`cut -d'|' -f18 <<< "$INFO"`"
	if [ "$ID3_ALBUMART" ]; then
		URL_ALBUMART=embedded
	else
		URL_ALBUMART="`cut -d'|' -f19 <<< "$INFO"`"
	fi
	#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
		TMP2="`echo "$TMP" | sed -e 's/^00//' -e 's/^0//'`"
		ID3_GENRE="`grep -Fm1 "(${TMP2})" $APPDIR/txt_id3genre | cut -d'(' -f1`"
	fi
	#write to db if new info. -read_quick is used by func_trackinfo while -read is used by func_index
	if [ "$2" != "-read_quick" ] && [ "SKIP_DB_WRITE" != "true" ]; then
		#ID3_ARTIST2 is used ONLY for db. This is not the tag, but db wants some info
		ID3_ARTIST2="$ID3_ARTIST"
		[ ! "$ID3_ARTIST2" ] && ID3_ARTIST2="`basename "$(echo "$INFO" | cut -d'|' -f1)"`"
		#The edited row must be placed first in case index_mymusic also contains data from quick_update. sort -u will delete the latter. 
		echo "$FILE|$ID3_ARTIST2|$ID3_TITLE|$ID3_ALBUM|$ID3_TRACK|$ID3_YEAR|$ID3_GENRE|$ID3_COMMENT|$RATING|$FF_FORMAT|$FF_BITRATE|$FF_LENGTH||$FILE|$ICON|$MB_DISC_ID|$MB_ARTIST_ID|$URL_LYRICS|$URL_ALBUMART||$RATING_TIMESTAMPS" > $WORKDIR/tmp_id3io_$SUFFIX
		( flock -e 200
			grep -vF "${FILE}|" "$DB" >> $WORKDIR/tmp_id3io_$SUFFIX
			mv -f $WORKDIR/tmp_id3io_$SUFFIX "$DB" # 2> /dev/null
		) 200>$WORKDIR/mymusic_db.lockfile 
	fi
	;;


-write)
	ID3_TITLE="`echo "$ID3_TITLE" | grep -vE "$TXT_SEARCHING|$TXT_NO_CONNECTION"`"
	ID3_ARTIST="`echo "$ID3_ARTIST" | grep -vE "$TXT_SEARCHING|$TXT_NO_CONNECTION"`"
	ID3_ALBUM="`echo "$ID3_ALBUM" | grep -vE "$TXT_SEARCHING|$TXT_NO_CONNECTION"`"
	ID3_YEAR="`echo "$ID3_YEAR" | grep -vE "$TXT_SEARCHING|$TXT_NO_CONNECTION"`"
	ID3_GENRE="`echo "$ID3_GENRE" | grep -vE "$TXT_SEARCHING|$TXT_NO_CONNECTION"`"
	ID3_TRACK="`echo "$ID3_TRACK" | grep -vE "$TXT_SEARCHING|$TXT_NO_CONNECTION"`"
	#ID3_COMMENT doesn't need to be verified
	#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" ] && [  "$TMP" -gt "0" ]; then #it contains a number
		TMP2="`echo "$TMP" | sed -e 's/^00//' -e 's/^0//'`"
		ID3_GENRE="`grep -Fm1 "(${TMP2})" $APPDIR/txt_id3genre | cut -d'(' -f1`"
	fi
	#---
	EXTENSION="`basename "$FILE" | sed -e "s/^.*\.//g"`"
	ffmpeg -i "$FILE" -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_$SUFFIX.$EXTENSION
	mv -f $WORKDIR/tmp_ffmpeg_copy_$SUFFIX.$EXTENSION "$FILE"
	#update db
	( flock -e 200
		if [ "`grep -F "$FILE" "$STORAGE_DIR/index_mymusic"`" ]; then
			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 "|" $18 "|" $19 "|" $20 "|" $21}' > $WORKDIR/tmp_id3io
			grep -Fv "$FILE" "$STORAGE_DIR/index_mymusic" >> $WORKDIR/tmp_id3io
			mv -f $WORKDIR/tmp_id3io "$STORAGE_DIR/index_mymusic"
		fi
	) 200>$WORKDIR/mymusic_db.lockfile
	#update gui
	if [ "$ID3_TITLE" ] && [ "$ID3_ARTIST" ]; then
		NEW_PLAYLIST_NAME="$ID3_ARTIST - $ID3_TITLE"
		update_lists
	fi
	#update playlist
	if [ "$ID3_TITLE" ] && [ "$ID3_ARTIST" ]; then
		NAME="`grep -Fm1 "|${FILE}|" $WORKDIR/playlist | cut -d'|' -f3`"
		( flock -e 201
			sed -i "s%|$NAME|%|$ID3_ARTIST - $ID3_TITLE|%g" $WORKDIR/playlist $WORKDIR/PLAYLIST_ALL
		) 201>$WORKDIR/playlist.lockfile 
		#update svg in main gui and now_playing file
		echo "|$FILE" > $HOME/.pmusic/nowplaying #this makes func_progressbar to activate full reading of playing track
		
	fi
	;;


-clear)
	EXTENSION="`basename "$FILE" | sed -e "s/^.*\.//g"`"
	FILENAME="`basename "$FILE"`"
	ffmpeg -i "$FILE" -acodec copy -id3v2_version 3 -metadata title='' -metadata artist='' -metadata album='' -metadata year='' -metadata track='' -metadata comment='' -metadata genre='' -y $WORKDIR/tmp_ffmpeg_copy_$SUFFIX.$EXTENSION
	mv -f $WORKDIR/tmp_ffmpeg_copy_$SUFFIX.$EXTENSION "$FILE"
	#update db
	( flock -e 200
		grep -F "$FILE" "$STORAGE_DIR/index_mymusic" | awk -F'|' -v VAR1="$FILENAME" '{print $1 "|" VAR1 "|||||||" $9 "|" $10 "|" $11 "|" $12 "|" $13 "|" $14 "|" $15 "|" $16 "|" $17 "|" $18 "|" $19 "|" $20 "|" $21}' > $WORKDIR/tmp_id3io
		grep -vF "${FILE}|" "$STORAGE_DIR/index_mymusic" >> $WORKDIR/tmp_id3io
		mv -f $WORKDIR/tmp_id3io "$STORAGE_DIR/index_mymusic"
	) 200>$WORKDIR/mymusic_db.lockfile
	#update gui
	NEW_PLAYLIST_NAME="$FILENAME"
	update_lists
	;;
esac

