l = require "luxio"

local req = "GET / HTTP/1.1\r\nHost: www.rjek.com\r\nConnection: close\r\n\r\n"

local r, errno

r, addrinfo = l.getaddrinfo("www.rjek.com", "80", 0, l.AF_UNSPEC, l.SOCK_STREAM)

if (r < 0) then
   io.stdout:write(("FAIL: getaddrinfo: %s\n"):format(l.gai_strerror(r)))
   os.exit(false)
end

local sock

for idx, ai in ipairs(addrinfo) do
   io.stdout:write(("STAT: trying suggestion %d...\n"):format(idx))
   for i, v in pairs(ai) do
      io.stdout:write(("STAT:  '%s' is '%s'\n"):format(tostring(i), tostring(v)))
   end
   
   sock, errno = l.socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)
   if (sock < 0) then
      io.stdout:write(("STAT:  can't create socket: %s\n"):format(l.strerror(errno)))
      sock = nil
   else
      r, errno = l.connect(sock, ai.ai_addr);
      if (r < 0) then
	 io.stdout:write(("STAT:  can't connect: %s\n"):format(l.strerror(errno)))
	 r, errno = l.close(sock)
	 if (r < 0) then
	    io.stdout:write(("FAIL: close: %s\n"):format(l.strerror(errno)))
	    os.exit(false)
	 end
	 sock = nil
      else
	 break -- we connected!
      end
   end
end

if (sock == nil) then
   io.stdout:write("FAIL: unable to find anything to connect to!\n")
   os.exit(false)
end

local sent = 0
while sent < #req do
   r, errno = l.write(sock, req, sent)
   if (r < 0) then
      io.stdout:write(("FAIL: write: %s\n"):format(l.strerror(errno)))
      os.exit(false);
   end
   
   sent = sent + r
   io.stdout:write(("STAT: wrote %d of %d bytes, %d total sent\n"):format(r, #req, sent))
end

repeat
   r, errno = l.read(sock, 1024)
   if (r == -1) then
      io.stdout:write(("FAIL: read: %s\n"):format(l.strerror(errno)))
      os.exit(false)
   end
      io.stdout:write(r)
until #r == 0

io.stdout:write("PASS: Well, possibly.\n")