-- Command-line-driven web client for mol2chemfig.
local os = require("os")
local io = require("io")

local json = require("json")
require("rpc") -- modifies json in place to add rpc namespace

local progname = arg[0]
local client_version = "1.2"

server = json.rpc.proxy(server_address)
local server_info, error = server.info({progname, client_version})

if error then
   io.stderr:write("Error: ", error)
   os.exit()
end

-- if we get here, the server responds as expected.

function printhelp()
   print (server_info['help_text'])
   os.exit()
end

-- Split input into options and arguments. Only arguments
-- at the end are accepted.

local arguments = {}
local i = #arg

if i == 0 then  -- no input at all
   printhelp()
end

noargs = server_info['noarg_shortopts']

-- separate options and arguments
while i > 0 and arg[i]:sub(1,1) ~= '-' do
   local j = i - 1

   if j == 0 or
             arg[j]:sub(1,1) ~= '-' or
             arg[j]:sub(2,2) == '-' or
             string.find(noargs, arg[j]:sub(2,2))
   then
       table.insert(arguments,#arguments+1,arg[i])
       table.remove(arg, i)
   end

   i = j
end

-- what remains in arg after removing arguments are options
local user_options = table.concat(arg, ' ')


-- first, see whether the user requests help or the program version.
local version_opts = server_info['version_opts']
local s

for i,s in ipairs(version_opts) do
   if string.find(user_options, s) then
       print(server_info['version_text'])
       print("On your system, the client is installed in: " .. progname)
       os.exit()
   end
end

local help_opts = server_info['help_opts']

for i,s in ipairs(help_opts) do
   if string.find(user_options, s) then
       printhelp()
   end
end

-- if we get here, the user should have provided exactly one argument.

if #arguments ~= 1 then
   print ('Please provide exactly one argument (must come last, after any options)')
   os.exit()
end

-- have exactly one argument. read it directly, or treat it as a file name?

local direct_input = false
local direct_opts = server_info['direct_opts']

for i,s in ipairs(direct_opts) do
   if string.find(user_options, s) then
       direct_input = true
   end
end

local data

if direct_input == false then
   f = io.open(arguments[1])
   if f then
       data = f:read("*all")
   else
       print ("File '" .. arguments[1] .. "' not found")
       os.exit()
   end
else
   data = arguments[1]
end

-- process options and data
local result, error = server.process({progname, user_options, data})

if error then
   io.stderr:write(error .. '\n')
else
   print(result)
end