#! /usr/bin/env lua

local p = require "posix"
local port = 54321

local short = "hp:arltq"
local long = {
	{"help", "none", 'h'},
	{"port", "required", 'p'},
	{"add", "none", 'a'},
	{"remove", "none", 'r'},
	{"list", "none", 'l'},
	{"test", "none", 't'},
	{"quit", "none", 'q'}
}

local cmd_assoc = {
	a = "add",
	r = "remove",
	l = "list",
	t = "test",
	q = "quit"
}

local cmd
local data_idx = 1
for opt, optarg, optind, longind in p.getopt(arg, short, long) do
	if opt == '?' then
		print("Unrecognized option")
		os.exit(1)
	elseif opt == 'h' then
		print("Usage: rulc [-h|-p PORT|-a|-r|-l|-t|-q] DATA ...")
		os.exit(0)
	elseif opt == 'p' then
		port = optarg
	else
		cmd = cmd_assoc[opt]
	end
	data_idx = optind
end

if not cmd then
	os.exit(1)
end

local msg = cmd
if cmd == "test" then
	msg = string.format("%s {class=%q, instance=%q, title=%q, type=%q, state=%q}", msg, arg[data_idx], arg[data_idx+1], arg[data_idx+2], arg[data_idx+3], arg[data_idx+4])
elseif cmd == "add" then
	msg = string.format("%s {%q, %q, %s}", msg, arg[data_idx], arg[data_idx+1], arg[data_idx+2] and string.format("{%s}", arg[data_idx+2]) or "")
elseif cmd == "remove" then
	msg = string.format("%s %s", msg, arg[data_idx])
end

local fd = p.socket(p.AF_INET, p.SOCK_STREAM, 0)
local s = p.connect(fd, {family=p.AF_INET, addr="127.0.0.1", port=port})
if not s then
	p.close(fd)
	os.exit(1)
end
p.send(fd, msg)
rsp = p.recv(fd, p.BUFSIZ)

if rsp and #rsp > 0 then
	print(rsp)
end

p.close(fd)
