#!/bin/lua

local function parse_url(url)
    if string.sub(url, 1, 4) == "http:" or string.sub(url, 0, 6) == "https:" then return url end
    return "http://" .. url
end

os.setproc("name", "curl")

if arg[1] == "-o" then
    if arg[2] and arg[3] then
        local url = parse_url(arg[3])
        local ok, body, status = pcall(socket.http.get, url)
        if ok then
            if status ~= 200 then
                print("status: " .. status)
                print("---")
                print(body)
                print("---")
            end

            local code = io.write(body, os.join(arg[2]))
            if code == 13 then
                print("curl: permission denied")
            elseif code == 5 then
                print("curl: read-only storage")
            elseif code == 1 then
                print("curl: java.io.IOException")
            end

            os.exit(tonumber(code))
        else
            print("curl: (6) Could not resolve host: " .. arg[3])
        end
    else
        print("Usage: curl -o [file] [url]")
    end
elseif arg[1] == "-s" then
    if arg[2] and arg[3] then
        print(pcall(os.request, arg[2], arg[3], arg[4]))
    else
        print("Usage: curl -s [pid] [request] [args]")
    end
elseif arg[1] then
    local url = parse_url(arg[1])
    local ok, body, status = pcall(socket.http.get, url)
    if ok then
        print(body)
    else
        print("curl: (6) Could not resolve host: " .. arg[1])
    end
else
    print("curl [url]")
end
