#!/usr/bin/env lua

-- usage: secret-tool store --label='label' attribute value ...
--        secret-tool lookup attribute value ...
--        secret-tool clear attribute value ...
--        secret-tool search [--all] [--unlock] attribute value ...

local action = ...

local options = {}
for line in io.stdin:lines() do
	local key, value = line:match("^(.*)=(.*)$")
	options[key]=value
end

if action == "get" then
	local command = string.format('secret-tool lookup application git username %s host %s', options.username, options.host, options.username, options.host)
	local file = assert(io.popen(command, "r"))
	local password = file:read("all")
	if password~="" then
		print("password="..password)
	else
		os.exit(1, true)
	end
	file:close()
elseif action == "store" then
	local command = string.format('secret-tool store --label="git %s@%s" application git username %s host %s', options.username, options.host, options.username, options.host)
	local file = assert(io.popen(command, "w"))
	file:write(options.password)
	file:close()
elseif action == "erase" then
	local command = string.format('secret-tool clear application git username %s host %s', options.username, options.host, options.username, options.host)
	os.execute(command)
end