-- vim: ft=terra
wftpl = lib.tpl.mk [[{
	"subject": @$subj,
	"aliases": [ @$href, @$pfp ],
	"links": [
		{ "rel": "self", "type": "application/activity+json", "href": @$href },
		{ "rel": "self",
			"type": "application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"", "href": @$href },
		{ "rel": "http://webfinger.net/rel/profile-page",
			"type": "text/html", "href": @$pfp }
	]
}]]

local terra 
webfinger(co: &lib.srv.convo)
	var res = co:pgetv('resource')
	lib.dbg('got webfinger request for resource ', {res.ptr,res.ct})
	if (not res) or not res:startswith 'acct:' then goto err end
	
	var acct = res + 5
	var svp = lib.str.find(acct, '@')
	if svp:ref() then
		acct.ct = (svp.ptr - acct.ptr)
		svp:advance(1)
		if not svp:cmp(co.srv.cfg.domain) then goto err end
	end

	var actor = co.srv:actor_fetch_xid(acct)
	if not actor then goto err end
	do defer actor:free()
		if actor().origin ~= 0 then goto err end
		var href = co:stra(64)
		var pfp = co:stra(64)
		href:lpush'https://':ppush(co.srv.cfg.domain):lpush'/user/':shpush(actor().id)
		pfp:lpush'https://':ppush(co.srv.cfg.domain):lpush'/@':ppush(acct)

		var tp = wftpl {
			subj = res;
			href = href:finalize();
			pfp = pfp:finalize();
		}
		co:json(tp:poolstr(&co.srv.pool))

		return
	end
	-- error conditions
	::err:: do co:json('{}') return end
end
return webfinger
