#!/bin/env lua

local escape_lua_pattern
do
    local matches =
    {
        ["^"] = "%^";
        ["$"] = "%$";
        ["("] = "%(";
        [")"] = "%)";
        ["%"] = "%%";
        ["."] = "%.";
        ["["] = "%[";
        ["]"] = "%]";
        ["*"] = "%*";
        ["+"] = "%+";
        ["-"] = "%-";
        ["?"] = "%?";
        ["\0"] = "%z";
    }

    escape_lua_pattern = function(s)
        return (s:gsub(".", matches))
    end
end

--[[
   Write file content back out to the file
--]]
function writefile(filename,lines)
   local configfile = assert(io.open(filename,"w"));
   for k,v in ipairs(lines) do
      configfile:write(v,"\n");
   end
   configfile:close();
end

--[[
   Read file configuration into table
--]]
function loadfile(filename)
   local filecontents = {}
   local configfile = assert(io.open(filename, "r"));
   for line in configfile:lines() do
      table.insert(filecontents,line);
   end
   configfile:close();
   return filecontents;
end

--[[
   Swop out server and port configuration options
--]]
function replace_config(filecontents, cfgserver, cfgport)

   for k,v in ipairs(filecontents) do
      old_server, old_port = v:match("remote%s+([^\r\n]+)%s+(%d+)")
      if old_server ~= nil then	 
	 v = "remote " .. cfgserver .. " " .. cfgport
	 filecontents[k] = v
      end
   end

end

function main(config_server,config_port)
   local cfgserver = config_server or 'www.ostb.co.za'
   local cfgport = config_port or 1194
   
   filecontents = loadfile("/etc/openvpn.conf");

   replace_config(filecontents,cfgserver,cfgport);
   
   writefile("/etc/openvpn.conf",filecontents);
end


local vpn_server = arg[1] or '196.213.199.170'
local vpn_port = arg[2] or 1194
main(vpn_server,vpn_port)
