# generate the following log files:
#	* twtxt gemini
#	* twtxt web
# 	* atom feed gemini
#	* atom feed web
#	* gmo log
#	* gmisub
# to use:
# awk -f genlog.awk log.txt

BEGIN{
	twgempath = "gem/tw.txt"
	twwebpath = "web/tw.txt"
	loggmopath = "src/log.gmo"
	atomwebpath = "web/atom.xml"
	atomgempath = "gem/atom.xml"
	gmisubpath = "gem/feed.gmi"

	loggmoheader = "log/logheader.gmi"
	gematomheader = "log/gematomheader.txt"
	webatomheader = "log/webatomheader.txt"
	gmisubheader = "log/feedheader.gmi"

	FS = "\t"

	"date --rfc-3339=date"| getline fecha

	system("cp " loggmoheader " " loggmopath)
	system("cp " gematomheader " " atomgempath)
	system("cp " webatomheader " " atomwebpath)
	system("cp " gmisubheader " " gmisubpath)

	updated = "<updated>" fecha "T12:00:00Z</updated>"
	print updated >> atomgempath
	print updated >> atomwebpath
	print "# nick = compudanzas" > twgempath
	print "# nick = compudanzas" > twwebpath
}

{
	# $1 es la fecha
	# $2 el texto
	# $3 el wikilink, opcional
	twgemstring = $1 "\t" $2
	twwebstring = $1 "\t" $2

	date = $1
	gsub(/T.+$/,"",date) # remove time from date

	print "## " date >> loggmopath
	printf "%s\n", $2 >> loggmopath

	# web atom feed
	printf "\n<entry>\n" >> atomwebpath
	print "<title>" $2 "</title>" >> atomwebpath
	print "<updated>" $1 "</updated>" >> atomwebpath

	# gem atom feed
	printf "\n<entry>\n" >> atomgempath
	print "<title>" $2 "</title>" >> atomgempath
	print "<updated>" $1 "</updated>" >> atomgempath

	if ( match($3, /{.+}/) ){ # si hay wikilink
		gsub("{","",$3)
		gsub("}","",$3)
		filename = $3
		gsub(" ","_",filename)

		print "=> ./" filename ".gmi {" $3 "}" >> loggmopath

		print "=> ./" filename ".gmi " date " " $2  >> gmisubpath

		gemurl = "gemini://compudanzas.net/" filename ".gmi"
		weburl = "https://compudanzas.net/" filename ".html"
		twgemstring = twgemstring " | " gemurl
		twwebstring = twwebstring " | " weburl

		print "<link rel='alternate' href='" weburl "#" date "'/>" >> atomwebpath
		print "<id>" weburl "#" date "</id>" >> atomwebpath

		print "<link rel='alternate' href='" gemurl "'/>" >> atomgempath
		print "<id>" gemurl "</id>" >> atomgempath
	}
	else{
		print "<link rel='alternate' href='https://compudanzas.net/log.html#" date "'/>" >> atomwebpath
		print "<id>https://compudanzas.net/log.html#" date "</id>" >> atomwebpath

		print "<link rel='alternate' href='gemini://compudanzas.net/log.gmi#" date "'/>" >> atomgempath
		print "<id>gemini://compudanzas.net/log.gmi#" date "</id>" >> atomgempath
	}
	print twgemstring > twgempath
	print twwebstring > twwebpath

	print "</entry>" >> atomwebpath
	print "" >> loggmopath
}

END {
	print "</feed>" >> atomwebpath

}
