-- vim: ft=terra

local util = dofile('common.lua')
local buildopts, buildargs = util.parseargs{...}

local config = dofile('config.lua')

local lib = {
	loadlib = function(name,hdr)
		local p = config.pkg[name]
		-- for _,v in pairs(p.dylibs) do
		-- 	terralib.linklibrary(p.libdir .. '/' .. v)
		-- end
		return terralib.includec(p.incdir .. '/' .. hdr)
	end;
	randomize = terralib.externfunction('getrandom', {&opaque, intptr, uint} -> ptrdiff);
}
lib.rsa = lib.loadlib('mbedtls','mbedtls/rsa.h')
lib.pk = lib.loadlib('mbedtls','mbedtls/pk.h')

local callbacks = {
	randomize = terra(ctx: &opaque, dest: &uint8, sz: intptr): int
		return lib.randomize(dest, sz, 0)
	end;
}

terra entry(): int
	var pk: lib.pk.mbedtls_pk_context
	lib.pk.mbedtls_pk_init(&pk)
	lib.pk.mbedtls_pk_setup(&pk, lib.pk.mbedtls_pk_info_from_type(lib.pk.MBEDTLS_PK_RSA))
	var rsa = [&lib.rsa.mbedtls_rsa_context](pk.pk_ctx)
	lib.rsa.mbedtls_rsa_gen_key(rsa, callbacks.randomize, nil, 2048, 65537)
	return 0
end

local bflag = function(long,short)
	if short and util.has(buildopts, short) then return true end
	if long and util.has(buildopts, long) then return true end
	return false
end

if bflag('dump-config','C') then
	print(util.dump(config))
	os.exit(0)
end

local emit = print
if bflag('quiet','q') then emit = function() end end

local out = config.exe and 'parsav' or 'parsav.o'
local linkargs = {}
for _,p in pairs(config.pkg) do util.append(linkargs, p.linkargs) end
emit('linking with args',util.dump(linkargs))
terralib.saveobj(out, {
		main = entry
	},
	linkargs,
	config.tgttrip and terralib.newtarget {
		Triple = config.tgttrip;
		CPU = config.tgtcpu;
		FloatABIHard = config.tgthf;
	} or nil)
