# See also scripts/pl

# Finds common music files in the current directory, optionally taking a regex
findsongs() {
	find -regextype posix-extended -maxdepth 1 -type f \
		-iregex "${1:-.*\.(mp3|flac|wav|m4a)}" -printf "%P\n"
}

addmix() {
	AUDIO="$DATA/audio"
	mv -v "$1.cue" "$AUDIO/recordings/cues"
	addsong "$1.flac" Mixes
}

# Used to keep music directory small, pretty much obsolete now
MUSIC_RAW="$d4/songs/_raw"

addsong() {
	test "$1" = "-q" && shift && quick="true"

	local raw="${1%.*}"
	local isflac=$(case "$1" in *.flac) echo "true";; esac)
	test "$isflac" || (echo "Converting to flac..." && flac "$1" --totally-silent)

	test "$quick" || (echo "Press ENTER when the metadata of the flac file is correct..." && read)

	echo "Converting to mp3..."
	lame -V0 "$1" --silent

	mkdir -p "$MUSIC/$2"
	mkdir -p "$MUSIC_RAW/$2"

	local destination="$MUSIC/$2/$raw.mp3"
	echo "Moving mp3 with metadata to $destination"
	ffmpeg -i "$raw.mp3" -i "$raw.flac" -c copy -map_metadata 1 "$destination" -v warning "${@:3}" && rm "$raw.mp3"
	test ! "$PWD" -ef "$MUSIC_RAW/$2" && mv -v "$raw.flac" "$MUSIC_RAW/$2" && (test "$isflac" || rm -v "$1")
}

# Execute inside an album folder with the desired target path
addalbum() {
	mkdir -p "$MUSIC/$1"
	mkdir -p "$MUSIC_RAW/$1"
	f1 -regextype posix-extended -type f -iregex "\./(cover|folder)\.(png|jpg|jpeg)" |
		while read cover; do
			foundcover="true"
			cp -v "$cover" "$MUSIC/$1" &&
			mv -v "$cover" "$MUSIC_RAW/$1"
		done
	test "$foundcover" || f1 -regextype posix-extended -type f -iregex ".*\.(png|jpg|jpeg)" |
		while read cover; do
			cp -v "$cover" "$MUSIC/$1" &&
			mv -v "$cover" "$MUSIC_RAW/$1"
		done

	IFS=$'\n'
	for s in $(findsongs ".*\.(flac|wav)"); do
		highlight "$s"
		addsong -q "$s" "$1" "${@:2}"
	done
	unset IFS
}


updatemusic() {
	for dir in $(find "$MUSIC" -mindepth 1 -maxdepth 1 -type d -name "[A-Z]*")
	do builtin cd "$dir"
	   find -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | while read dir
       do target="$(echo ${dir} | tr -d ' ')"
		  find -maxdepth 1 \( -name "$dir" -o -iname "$(echo ${target} | sed 's/\([a-z]\)\([A-Z][a-z]\)/\1*\2/g')*" \) -not -name "$target" -exec mv -nv {} $target/ \;
       done
	done
	cd "$MUSIC"
	find -mindepth 4 -type d -not -path '*/Hip-Hop/*' -not -path '*/Movies/*' -not -path '*/LeagueOfLegends/*' -exec sh -c 'mv -vn "{}" "$(echo "{}" | cut -d/ -f2-3)/"' \; -prune
	find -mindepth 4 -type d -exec sh -c 'test $(find "{}" -type f | grep -vE "(.jpe?g|.png)" | wc -l) -eq 1 && name="$(ls "{}" | grep -vE "(.jpe?g|.png)")" && mv -vi "{}/$name" "$(dirname "{}")/$(echo "$name" | sed "s|^01 ||")" && rm -rv "{}"' \; -prune
	# TODO delete folders with only images: find -type d -exec sh -c 'test $(find "{}" -type f | grep -vE "(.jpe?g|.png)" | wc -l) -eq 0 && rm -r "{}"' \; -prune
	find -empty -delete
	formatsongs
	printf "=== DONE RENAMING ===\n\n"
	beet import -AC "$MUSIC"
}

formatsongs() {
	(
	find -mindepth 1 -maxdepth 1 -type d -printf '%f\n' | formatin
	find "${@:-$PWD}" -type d | while read d;
		do builtin cd "$d" && findsongs | formatin
		   test $(find -maxdepth 1 -name '01 *' | wc -l) -gt 1 -a $(find -maxdepth 1 -name '02 *' | wc -l) -eq 0 &&
		     zmv -W '01 *' '*'
		done
	)
	# fd --no-ignore-vcs --type f --extension opus --exec opusdec --quiet "{}" "{.}.wav" \; ".*" "$@"
	find "$@" -type f -iname "*.wav" -exec sh -c '
		f="{}" &&
		echo "Converting $f to ${f%.*}.flac" &&
		ffmpeg -i "$f" "${f%.*}.flac" -v warning &&
		mv -v "$f" /tmp' \;
}

# Normalize filenames for files given from stdin
formatin() {
	while read song; do
		new="$(formatsong "$song")"
		if test "$new" && test "$new" != "$song"
		then mkdir -p "$(dirname "$new")" && mv -iv "$song" "$new"
		fi
	done
}

# Normalize the given filename
formatsong() {
	# Qobuz folders /^[A-z0-9_-]\+$/{s|_| |g;s|-|/|g};
	echo "$1" | sed -e '
		s/\b\(ft\|Ft\|Feat\|featuring\)\([ .]\)/feat\2/;
		s/\bfeat /feat. /;
		s/)(/) (/g;
		s/ [[(]\(None\|Free Download\|Original Mix\|Original\|Full Stream\|NCS Release\)[])]//i;
		s/ (\(Acoustic\|Live|.* Remix\))/ [\1]/i;
		s/ \[\(feat.*\)\]/ (\1)/i;
		s/ \(\..\{2,4\}\)$/\1/;
		s/---/ - /;
		s/-LLS\././;
		s/^[0-9]\{6\}_//;
		s/\([^/]\)_/\1 /g;
		s/ \././g;
		s/  / /g;
		s/\(\w\)+\(\w\)/\1 \2/g' -
		#s/^\([A-z]\+\) The \([^-]\+\)$/\1, the \2/g;
}