#!/bin/bash
# usage: extract-annotations.sh >import-annotaions.sh

root=~

# collect file/directory paths
echo "collecting file names" >&2
filelist=$(mktemp -t 'noteFileListXXXX')
find "$root" >"$filelist" 2>/tmp/note-find-errors

# extract data
echo "collecting meta information" >&2
info=$(mktemp -t 'noteInfoXXXX')
while IFS= read -r f ; do
	echo "$f"  >>"$info"
	gio info "$f" >>"$info"
	#gvfs-info "$f" >>"$info"
	echo $'\f' >>"$info"
done < "$filelist"

rm "$filelist"

# generate output
echo "generating output" >&2
gawk -f <(cat - <<-'_EOF_'
	BEGIN {
		trace = 0
		state = 0
		file = ""
		buf = ""
		numFiles = 0
		# if (trace) print  "<state " state "> "
		print "#!/bin/bash\n"
	}
	
	state == 0 {
		# file name
		file = "\"" $0 "\""
		# if (trace) printf  "<state %d> %s\n", state, file
		buf = ""
		state = 1
		next
	}
	
	state == 1 && /\f/ {
		# if (trace) print  "<state " state "> "
		state = 0
		next
	}
	
	state == 1 && /metadata::annotation/ {
		# first metadata::annotation
		# if (trace) print  "<state " state "> "
		gsub(/^  metadata::[^:]+: /, "")
		if (!match($0, /^\s*$/))
			buf = buf $0 "\n"
		numFiles++
		state++
		next
	}

	state >= 2 && /\f/ {
		# ff – output, if buf contains data
		# if (trace) print  "<state " state "> \"" $0 "\""
		if (!match(buf, /^\s*$/)) {
			gsub("'", "\\'", buf)
			printf "gio set %s metadata::annotation '%s'\n", file, buf
		}
		state = 0
		next
	}
	
	state == 2 && /metadata::/ {
		# metadata::*
		# if (trace) print  "<state " state "> \"" $0 "\""
		state++
		next
	}
	
	state == 2 {
		# anything between metadata::annotation and ff
		# if (trace) print  "<state " state "> \"" $0 "\""
		buf = buf  $0 "\n"
		next
	}
	
	END {
		printf "Number of notes found: %d\n", numFiles >"/dev/stderr"
	}
_EOF_
) "$info"

rm "$info"
