-- Light Unix I/O for Lua
-- Copyright 2012 Rob Kendrick <rjek+luxio@rjek.com>
--
-- Distributed under the same terms as Lua itself (MIT).
--
-- A wrapper around the rather raw interface luxio normally provides to
-- make things simpler.

--- High-level bindings to POSIX functionality.
--- @module luxio.simple

--
-- sio = require "luxio.simple"
--
-- sio.stdin, .stdout, .stderr
--         descriptor objects for standard IO end points
--
-- myfile = assert(sio.open("filename", "flags"[, "mode"]))
--          flags is a string, each flag is a single character:
--             r = open for reading (O_RDONLY)
--             w = open for writing (O_WRONLY)
--             + = open in append mode (O_APPEND)
--             c = create file if it does not already exist (O_CREAT)
--             e = ensure this call creates the file (O_EXCL)
--             n = do not update the access time (O_NOATIME)
--             d = where possible, open non-blocking (O_NONBLOCK)
--             t = truncate file if it already exists (O_TRUNC)
--
--             returns file object, or nil, error string, errno.
--
-- myfile.fd
--         file descriptor number of the object
--
-- myfile.name
--         descriptive name of file (such as file name, sockaddr, etc)
--
-- myfile.closed
--         bool indicating if this descriptor has been closed
--
-- myfile:close()
--         close the file.
--         returns true, or nil, errorstring, errno.
--
-- myfile:nonblocking([bool])
--         bool: true to set non-blocking, false to set blocking, nil to
--               make no change
--         returns bool indicating current state, or nil, error string and
--         errno.
--
-- myfile:write(string[, offset])
--         writes string to the file, optionally starting at offset bytes in
--         returns number of bytes written, or nil, error string, errno
--
-- myfile:writev(...)
--         writes ALL the strings!
--         return number of bytes written, or nil, error string, errno
--
-- myfile:seek([whence][, offset])
--         seek within the file.  whence can be one of cur, set and end.
--         values default to cur and 0.
--         returns new offset, or nil, error string, errno
--
-- myfile:read(pattern[, pattern...])
--         reads data from the file.  pattern can be:
--         a number: read this number of bytes.
--         "*a": read all data until EOF
--         "*l": read a line (warning: inefficient, reads a byte at a time!)
--         returns the results, or nil, error string, errno
--
-- myfile:chmod(mode)
--         Change permissions of an open descriptor's backing file.
--
-- myfile:nogc()
--         do not close the descriptor on garbage collect
--
-- myfile:lock(mode, whence, start, len, wait)
--         Manipulates advisory locks on file regions.
--         mode is one of "r", "w", or "", for read lock, write lock, or
--         unset lock.  whence, like seek, one of "cur", "set", "end".
--         start and len describe the region.  If wait is set, it will
--         wait until the lock is available before claiming it and
--         returning.
--
-- myfile:unlock(whence, start, len)
--         Same as above, except implicitly passes "" on your behave in mode
--
-- myfile:locktest(mode, whence, start, len)
--         As above, but it does not claim the lock, just checks if it
--         is available.  Returns true if the lock would work, or false
--         and a pid of the holder if the lock is already taken.
--
-- myfile = sio.wrap_fd(fd[, nogc][, name])
--         wrap an fd aquired elsewhere with functions here
--         fd: number of file descriptor
--         nogc: do not close file when object is collected (default false)
--         name: symbolic name of descriptor (default "<unknown>")
--
-- read_pipe, write_pipe = sio.pipe()
--         create an anonymous pipe, returning both halves, the read end and
--         the write end, or nil, error message, errno.
--
-- sock1, sock2 = sio.socketpair()
--         creates a pair of stream UNIX domain sockets, returning both.
--         Optionally pass luxio.SOCK_DGRAM if you want a datagram socket.
--
-- mysock = sio.inet([socktype])
--         create an IPv4 socket of socktype, either "tcp" (default) or "udp".
--         returns socket object or nil, error string, errno
--
-- mysock = sio.inet6([socktype])
--         create an IPv6 socket of socktype, either "tcp" (default) or "udp".
--         returns socket object or nil, error string, errno
--
-- mysock = sio.connect(host, service)
--         connects to a remote host via tcp, using getaddrinfo() to find
--         possibilities.  Does resolving, and can connect to both IPv4 and
--         IPv6 hosts.  returns socket object, or nil, error string, errno.
--
-- mysock = sio.bind(host, service[, backlog])
--         creates a TCP socket and binds it to the specified host and service.
--         returns socket object or nil, error string, errno
--
-- mysock:connect(address, port)
--         connects to an address and port.  No host name lookup is done.
--         returns true, or nil, error string, errno.
--
-- mysock:bind(address, port)
--         binds to an address and port.  No host name lookup is done.
--         returns true, or nil, error string, errno
--
-- mysock:listen([backlog])
--         enables listening for connections.
--         returns true, or nil, error string, errno
--
-- mysock:accept()
--         returns the next connection in the queue as a socket object, or
--         nil, error string, errno
--
-- mysock:setsockopt(level, option, value)
--         sets a socket option, such as SOL_SOCKET, SO_REUSEADDR.
--         returns true, or nil, error message, errno
--
-- mysock:getsockopt(level, option)
--         gets a socket option
--         returns the value, or nil, error message, errno
--
-- oldmask = sio.umask(newmask)
--         change the umask
--         returns old umask
--
-- chmod(filename, mode)
--         Changes the permissions of a named file
--
-- opendir(path)
--         Returns an object for directory enumeration,
--         or nil, error message, errno
-- mydir:iterate()
--         Returns an iterator suitable for use with the for loop that
--         returns two values, a file name and a table containing
--         d_ino, d_name and possibly d_type.
-- mydir:next()
--         Returns a table containing d_ino, d_name and possibly d_type,
--         or nil at end of directory.
-- mydir:close()
--         Closes an open directory.
--
-- mkdir(path[, "mode"])
--         Creates a directory.  Mode defaults to 0775.
--         Returns 0, or nil, errmsg, errno
--
-- fork()
--         Forks the process.  Returns 0 to the child, pid of child to
--         parent, or nil, errmsg, errno
-- exec(path, ...)
--         Replaces this proces with another.  Either never returns, or
--         returns nil, errmsg, errno
-- waitpid([pid[, options]])
--         Waits for a child to exit, and returns its exit status.  pid
--         defaults to -1.
-- kill(pid[, signal])
--         Sends a signal to another process.  Signal defaults to SIGTERM.
--         Returns 0, or nil, errmsg, errno
-- setenv(key, value[, overwrite])
--         Sets an environment variable.  overwrite defaults to false.
--         Returns 0, or nil, errmsg, errno
-- getenv(key)
--         Returns the given environment variable, or nil.
-- unsetenv(key)
--         Unsets the given key.  Returns 0 if success (or key didn't
--         exist) or nil, errmsg, errno
-- chdir(path)
--         Changes the current working directory.   Returns 0, or
--         nil, errmsg, errno
-- getcwd()
--         Returns the current working directory, or nil, errmsg, errno
--
-- flags()
--         Parses a list of comma-seperated flag strings, looks them up
--         as UNIX constants, and ORs them together.
--         Common suffixes are optional, and the system is case-insensitive.
--         For example, flags("rdrw,creat,excl") would be the same as ORing
--         together O_RDWR, O_CREAT, and O_EXCL.

local l = require "luxio"

assert(l._ABI == 0, "luxio ABI mismatch")

local l_open = l.open
local l_pipe = l.pipe
local l_socketpair = l.socketpair
local l_socket = l.socket
local l_bind = l.bind
local l_connect = l.connect
local l_listen = l.listen
local l_accept = l.accept
local l_close = l.close
local l_write = l.write
local l_writev = l.writev
local l_read = l.read
local l_stat = l.stat
local l_lstat = l.lstat
local l_fstat = l.fstat
local l_lseek = l.lseek
local l_chmod = l.chmod
local l_fchmod = l.fchmod
local l_umask = l.umask
local l_link = l.link
local l_mkdir = l.mkdir
local l_mkfifo = l.mkfifo
local l_unlink = l.unlink
local l_rmdir = l.rmdir
local l_rename = l.rename
local l_fcntl = l.fcntl
local l_setsockopt = l.setsockopt
local l_getsockopt = l.getsockopt
local l_getaddrinfo = l.getaddrinfo
local l_send = l.send
local l_sendto = l.sendto
local l_recv = l.recv
local l_recvfrom = l.recvfrom
local l_gai_strerror = l.gai_strerror
local l_connect = l.connect
local l_bit_bor = l.bit.bor
local l_bit_bclear = l.bit.bclear
local l_bit_btest = l.bit.btest
local strerror = l.strerror
local l_make_sockaddr = l.make_sockaddr

local getmetatable = getmetatable
local setmetatable = setmetatable
local assert = assert
local error = error
local tostring = tostring
local tonumber = tonumber
local unpack = unpack
local newproxy = newproxy

local lua_version = tonumber(_VERSION:match "Lua (%d.%d)")

local descriptor_mt

local sio_wrap_mt

local function err(s, errno)
    return nil, ("%s: %s"):format(s, strerror(errno)), errno
end

local function sio_mt_gc(o)
    if o.fd and not o.nogcfd then
        l_close(o.fd)
    end
end

--- stat result table.
--- The table that all the stat family returns.
--- @field dev ID of device containing file
--- @field ino inode number
--- @field mode protection mode
--- @field nlink number of hard links
--- @field uid user ID of owner
--- @field gid group ID of owner
--- @field rdev device ID (if special file)
--- @field size total size, in bytes
--- @field blksize blocksize for file system I/O
--- @field blocks number of 512 byte blocks allocated
--- @field atime time of last access
--- @field mtime time of last modification
--- @field ctime time of last status change
--- @table stat


--- A file handle.
--- The basic type used to expose file handles.
--- @type file

if lua_version == 5.1 then
    sio_wrap_mt = function(fd, nogcfd, name)
        assert(type(fd) == "number", "expected file descriptor number at #1")
        local p = newproxy(true)
        local r = { 
          --- The file descriptor as a number.
          fd = fd,
          proxy = p,
          nogcfd = nogcfd,
           --- Helpful text representation of file handle.
          name = name,
          closed = false }
        getmetatable(p).__gc = function()
            return sio_mt_gc(r)
        end
        return setmetatable(r, descriptor_mt)
    end
elseif lua_version >= 5.2 then
    sio_wrap_mt = function(fd, nogcfd, name)
        assert(type(fd) == "number", "expected file descriptor number at #1")
        local r = { fd = fd, nogcfd = nogcfd, name = name, closed = false }
        return setmetatable(r, descriptor_mt)
    end
end

local function sio_check_mt(t)
    if getmetatable(t) ~= descriptor_mt then
        error "not passed an sio object"
    end

    if t.closed then
        error "passed closed sio object"
    end

    return true
end

--- Close an open file.
--- @function file:close
--- @treturn bool|nil true on success, nil on failure
--- @treturn string|nil string describing error
--- @treturn errno|nil errno on error
local function close(o)
    sio_check_mt(o)

    local r, errno = l_close(o.fd)
    if r ~= 0 then
        return err("close", errno)
    end

    o.fd = nil
    o.closed = true

    return true
end

--- Disable garbage collection of a file.
--- @function file:nogc
local function nogc(o)
    sio_check_mt(o)

    o.nogcfd = true
end

--- Set the non-blocking flag on a file.
--- @function file:nonblocking
--- @tparam bool blocking true for non-blocking, false or nil for blocking.
local function nonblocking(o, b)
    sio_check_mt(o)

    local fd = o.fd
    local flags, errno = l_fcntl(fd, l.F_GETFL)

    if flags == -1 then
        return err("fcntl", errno)
    end

    if b == nil then
        return l_bit_btest(flags, l.O_NONBLOCK)
    elseif b == false then
        flags = l_bit_bclear(flags, l.O_NONBLOCK)
    elseif b == true then
        flags = l_bit_bor(flags, l.O_NONBLOCK)
    else
        error "expected nil, true or false at #2"
    end

    flags, errno = l_fcntl(fd, l.F_SETFL, flags)

    if flags ~= 0 then
        return err("fcntl", errno)
    else
        return true
    end
end

--- Write data to a file.
--- @function file:write
--- @tparam string data
--- @tparam[opt=1] number offset into string to start write from
--- @treturn number|nil bytes written, or nil on error
--- @treturn string|nil string describing error if error
--- @treturn errno|nil errno if error
local function write(o, d, i)
    sio_check_mt(o)
    assert(type(d) == "string", "string expected at #2")
    local r, errno = l_write(o.fd, d, i)

    if r < 0 then
        return err("write", errno)
    end

    return r
end

--- Write a list of strings to a file.
--- @function file:writev
--- @tparam string ... List of strings to write
--- @treturn number|nil Bytes written, or nil in case of error
--- @treturn string|nil string describing error if error
--- @treturn errno|nil errno if error
local function writev(o, ...)
    sio_check_mt(o)
    local r, errno = l_writev(o.fd, ...)

    if r < 0 then
        return err("writev", errno)
    end

    return r
end

--- Read data from a file.
--- This function takes a list of patterns to read, based loosely
--- on Lua's own read function.  They are:
---
---  * "*a" - read all data until end of file.
---  * "*l" - read a single line of data, or until end of file.
---  * Or, a number describing the number of bytes to read.
--- @function file:read
--- @tparam string ... List of read patterns.
--- @treturn ...|nil List of return strings, or nil if error
--- @treturn string|nil String describing error if error
--- @treturn errno|nil errno if error
local function read(o, ...)
    local res = { }
    for idx, patt in ipairs { ... } do
        if patt == "*a" then
            local c = { }
            repeat
                local r, errno = l_read(o.fd, l.BUFSIZ)
                if r == -1 then
                    return err("read", errno)
                end
                c[#c + 1] = r
            until #r == 0
            if #c ~= 0 then
                res[#res + 1] = table.concat(c)
            end

        elseif patt == "*l" then
            local c = { }
            local r, errno
            repeat
                r, errno = l_read(o.fd, 1)
                if r == -1 then
                    return err("read", errno)
                end
                if r ~= '\n' and #r ~= 0 then
                    c[#c + 1] = r
                else
                    break
                end
            until #r == 0
            if #c ~= 0 or #r ~= 0 then
                res[#res + 1] = table.concat(c)
            end

        elseif type(patt) == "number" then
            local r, errno = l_read(o.fd, patt)
            if r == -1 then
                return err("read", errno)
            end
            if #r ~= 0 then
                res[#res + 1] = r
            end
        else
            error(("unknown pattern specification '%s' at #%d"):format(patt, idx))
        end
    end

    if #res == 0 then
        return nil
    else
        return unpack(res)
    end
end

--- Get information on an option file.
--- @function file:fstat
--- @treturn stat|nil stat table or nil if error
--- @treturn string|nil string describing error if error
--- @treturn errno|nil errno if error
local function fstat(o)
    sio_check_mt(o)
    local r, e = l_fstat(o.fd)

    if r < 0 then
        return err("fstat", e)
    end

    return e
end

local seek_modes = {
    ["cur"] = l.SEEK_CUR,
    ["set"] = l.SEEK_SET,
    ["end"] = l.SEEK_END
}

--- Change the position within a file.
--- @function file:seek
--- @tparam string whence one of "cur", "set", and "end".
--- @tparam number offset signed number describing requested change.
--- @treturn number|nil resulting offset, as measured from beginning of file
--- in bytes, or nil if error.
--- @treturn string|nil string describing error if error
--- @treturn errno|nil errno if error
local function seek(o, whence, offset)
    sio_check_mt(o)
    assert(offset == nil or type(offset) == "number", "offset number expected at #2")
    whence = whence or "cur"
    offset = offset or 0

    whence = seek_modes[whence] or error "unknown seek whence"
    local r, errno = l_lseek(o.fd, offset, whence)

    if r < 0 then
        return err("lseek", errno)
    end

    return r
end

--- Apply or remove an advisory lock on an open file.
--- @function file:lock
--- @tparam string rw Lock type "r" for read, "w" for write, "" for unlock.
--- @tparam string whence one of "cur", "set", and "end"
--- @tparam number offset offset of start of lock/unlock location
--- @tparam number len length in bytes of lock/unlock locations
--- @tparam bool wait true if the call should block until region is unlocked
--- @tparam bool test true if you simply want to check if locked
--- @treturn true|nil nil if error
--- @treturn string|nil string describing error if error
--- @treturn errno|nil errno if error
local function lock(o, rw, whence, offset, len, wait, test)
    sio_check_mt(o)
    assert(rw == "r" or rw == "w" or rw == "")
    assert(seek_modes[whence])
    assert(type(offset) == "number")
    assert(type(len) == "number" and len >= 0)

    local flock = {
        l_whence = seek_modes[whence],
        l_start = offset,
        l_len = len
    }

    local cmd = wait and l.F_SETLKW or l.F_SETLK
    if test then cmd = l.F_GETLK end

    if rw == "r" then flock.l_type = l.F_RDLCK
    elseif rw == "w" then flock.l_type = l.F_WRLCK
    else flock.l_type = l.F_UNLCK
    end

    local r, errno = l_fcntl(o.fd, cmd, flock)

    if r < 0 then
        return err("fcntl", errno)
    end

    if not test then
        return true
    else
        if flock.l_type == l.F_UNLCK then
            return true
        else
            return false, flock.l_pid
        end
    end
end

--- Unlock a region of an open file.
--- Convienence function.  Simply calls `file:lock` with an empty rw.
--- @function file:unlock
--- @tparam string whence
--- @tparam number offset
--- @tparam number len
--- @treturn true|nil nil if error
--- @treturn string|nil string describing error if error
--- @treturn errno|nil errno if error
local function unlock(o, whence, offset, len)
    return lock(o, "", whence, offset, len)
end

local function locktest(o, type, whence, offset, len)
    return lock(o, type, whence, offset, len, false, true)
end

local function fchmod(o, mode)
    sio_check_mt(o)
    local mode = sio_mode_flags(mode)
    local r, errno = l_fchmod(o.fd, mode)

    if r < 0 then
        return err("fchmod", errno)
    end

    return r
end

--- Helper functions.
--- @section helper

local flag_prefixes = {
    "O_", "SEEK_", "SPLICE_F_", "S_", "F_", "PF_", "AF_", "IPPROTO_", "SOCK_",
    "SHUT_", "SO_", "TCP_", "AI_", "POLL", "LOG_", "EXIT_", "MSG_"
}

local function flags_find_flag(f)
    for flag in pairs(l) do
        if type(l[flag]) == "number" then
            if f == flag or f == flag:lower() then return flag end
            -- now look for both lower and upper using a set of prefixes
            for _, prefix in ipairs(flag_prefixes) do
                local try = prefix .. f
                if try == flag or try:upper() == flag:upper() then return flag end
            end
        end
    end
    
    return nil
end

local flag_cache = { }

--- Convert a string of comma-seperated flag names to a number.
--- This function takes a list of strings, each with comma-seperated flag names
--- and returns a number which is all of those flags ORed together.
--- Flags can optionally be lower-case, and also if they begin with one of
--- the common prefixes, such as O_, S_, F_, AF_, AI_, SO_, TCP_ and many others
--- can be omitted.
--- For example:
---
---     myflags = sio.flags "rdwr,creat,excl"
--- @tparam string ...
--- @treturn number
--- @function flags
local function flags(...)
    local r = 0
    local f = table.concat({ ... }, ",")
    
    if flag_cache[f] then return flag_cache[f] end
    
    
    for i in f:gmatch("([^,]*)") do
        if i ~= "" then
            local flag = flags_find_flag(i)
            if not flag then
                error("unknown flag " .. i)
            end
            r = l_bit_bor(r, luxio[flag])
        end
    end
    
    flag_cache[f] = r
    
    return r
end

local function sio_perm_flags_help(s, read, write, execute, sid)
    local c = { }
    for l in s:gmatch "." do
        if l == "r" then c[#c + 1] = read
        elseif l == "w" then c[#c + 1] = write
        elseif l == "x" then c[#c + 1] = execute
        elseif l == "s" then c[#c + 1] = sid
        elseif l == "t" then c[#c + 1] = l.S_ISVTX
        elseif l == "-" then -- skip -
        else error(("unknown permission flag '%s'"):format(l))
        end
    end

    return l_bit_bor(unpack(c))
end

local S_IRALL = l_bit_bor(l.S_IRUSR, l.S_IRGRP, l.S_IROTH)
local S_IWALL = l_bit_bor(l.S_IWUSR, l.S_IWGRP, l.S_IWOTH)
local S_IXALL = l_bit_bor(l.S_IXUSR, l.S_IXGRP, l.S_IXOTH)
local S_ISUIDGID = l_bit_bor(l.S_ISUID, l.S_ISGID)

--- Convert a string representing a permissions mode to a number.
--- This function converts a string into a mode flag.  It supports
--- many different forms.  For example:
---
---    sio.tomode(0666) -- already a mode, it'll just return it
---    sio.tomode "666" -- converted directly to number, assumed octal
---    sio.tomode "-rw-r--r--" -- as emitted by ls
---    sio.tomode "o+rw,g+r" -- as used by chmod
--- @tparam number|string f mode description to convert
--- @treturn number
--- @function tomode
local function sio_mode_flags(f)
    if type(f) == "number" then
    -- is already a suitable mode
        return f
    end

    if type(f) ~= "string" then
    -- if it's not a string, we don't know how to process it
    error("string describing access mode expected")
    end

    if f:match "0?[0-7][0-7][0-7][0-7]" then
        -- octal number as a string
        return tonumber(f, 8)
    end

    if not f:match "[^-rwx]" then
        -- ls-style
        local usr, grp, oth = f:match "(...)(...)(...)"
        if not (usr and grp and oth) then
            error "incorrect format for ls-style permissions flags"
        end
        local m = l_bit_bor(sio_perm_flags_help(usr, l.S_IRUSR, l.S_IWUSR, l.S_IXUSR),
            sio_perm_flags_help(grp, l.S_IRGRP, l.S_IWGRP, l.S_IXGRP),
            sio_perm_flags_help(oth, l.S_IROTH, l.S_IWOTH, l.S_IXOTH))
        return m
    end

    -- try to parse this as a chmod-style command
    local m = 0
    for e, p in f:gmatch "(.)=([^,]+),?" do
        if e == "u" then
            m = l_bit_bor(m, sio_perm_flags_help(p, l.S_IRUSR, l.S_IWUSR, l.S_IXUSR, l.S_ISUID))
        elseif e == "g" then
            m = l_bit_bor(m, sio_perm_flags_help(p, l.S_IRGRP, l.S_IWGRP, l.S_IXGRP, l.S_ISGID))
        elseif e == "o" then
            m = l_bit_bor(m, sio_perm_flags_help(p, l.S_IROTH, l.S_IWOTH, l.S_IXOTH, 0))
        elseif e == "a" then
            m = l_bit_bor(m, sio_perm_flags_help(p, S_IRALL, S_IWALL, S_IXALL, S_ISUIDGID))
        else
            error(("unknown access group '%s'"):format(e))
        end
    end

    return m
end

local open_flags = {
    r = 0, w = 0,  -- handled manually
    ["+"] = l.O_APPEND,
    c = l.O_CREAT,
    e = l_bit_bor(l.O_EXCL, l.O_CREAT),
    n = l.O_NOATIME,
    d = l.O_NDELAY,
    t = l.O_TRUNC
}

local function sio_open_flags(flags)
    local r = { }
    if flags:match "r" and flags:match "w" then
        r[#r + 1] = l.O_RDWR
    elseif flags:match "r" then
        r[#r + 1] = l.O_RDONLY
    elseif flags:match "w" then
        r[#r + 1] = l.O_WRONLY
    end

    for m in flags:gmatch "(.)" do
        local f = open_flags[m] or error(("unknown open flag '%s'"):format(m))
        r[#r + 1] = f
    end

    return l_bit_bor(unpack(r))
end

--- Opening files.
--- @section open

--- Open a file.
--- The open type may contain the following characters;
---
---   * r - open file for reading
---   * w - open file for writing
---   * \+ - append
---   * e - open and create exclusively (O_EXCL and O_CREAT)
---   * c - create file if it doesn't exist. (O_CREAT)
---   * n - do not modify access time (O_NOATIME)
---   * d - open in non-blocking mode (O_NDELAY)
---   * t - truncate file
--- @tparam string filename
--- @tparam[opt="r"] string flags open type
--- @tparam[opt] mode number permissions mode if creating.
--- @treturn file|nil File handle, or nil if error
--- @treturn string|nil Error string if error
--- @treturn errno|nil Error number if error
--- @function open
local function open(filename, flags, mode)
    mode = mode or tonumber("666", 8)
    assert(type(filename) == "string", "filename string expected at #1")
    flags = sio_open_flags(flags or "r")

    local r, errno = l_open(filename, flags, sio_mode_flags(mode))
    if r < 0 then
        return err("open", errno)
    end

    return sio_wrap_mt(r, false, filename)
end

local pipe_count = 0

--- Create an anonymous pipe.
--- Returns two files, the first one can be used to read data written
--- to the second.
--- @treturn file|nil Reading half of pipe, or nil on error
--- @treturn file|string Writing half of pipe, or string describing error
--- @treturn errno|nil Error number if error
--- @function pipe
local function pipe()
    local fds = { }
    local r, errno = l_pipe(fds)

    if r ~= 0 then
        return err("pipe", errno)
    end

    local pipename1 = ("<anonpipe %d/reader>"):format(pipe_count)
    local pipename2 = ("<anonpipe %d/writer>"):format(pipe_count)
    pipe_count = pipe_count + 1

    return sio_wrap_mt(fds[1], false, pipename1),
        sio_wrap_mt(fds[2], false, pipename2)
end

local socketpair_count = 0

--- Create an anonymous UNIX domain socket pair.
--- Returns two files, which can be considered as each end of a bi-directional
--- pipe.
--- @treturn file|nil First socket of the pair, or nil on error
--- @treturn file|string Second socket of the pair, or string describing error
--- @treturn errno|nil Error number if error
--- @function pipe
local function socketpair(type)
    type = type or l.SOCK_STREAM
    local typen = type == l.SOCK_STREAM and "stream" or "datagram"
    local sv = { }
    local r, errno = l_socketpair(l.AF_UNIX, type or l.SOCK_STREAM, 0, sv)

    if r ~= 0 then
        return err("pipe", errno)
    end

    local spname1 = ("<%s socketpair %d/0>"):format(typen, socketpair_count)
    local spname2 = ("<%s socketpair %d/1>"):format(typen, socketpair_count)
    socketpair_count = socketpair_count + 1

    return sio_wrap_mt(sv[1], false, spname1), sio_wrap_mt(sv[2], false, spname2)
end

local function stat(p)
    local r, e = l_stat(p)

    if r < 0 then
        return err("stat", e)
    end

    return e
end

local function lstat(p)
    local r, e = l_lstat(p)

    if r < 0 then
        return err("lstat", e)
    end

    return e
end

local function chmod(file, mode)
    local mode = sio_mode_flags(mode)
    local r, errno = l_chmod(file, mode)

    if r < 0 then
        return err("chmod", errno)
    end

    return r
end

local function umask(mask)
    return l_umask(sio_mode_flags(mask))
end

local function link(existing, new)
    local r, errno = l_link(existing, new)

    if r ~= 0 then
        return err("link", errno)
    end

    return true
end

local function mkfifo(pathname, mode)
    local mode = sio_mode_flags(mode)
    local r, errno = l_mkfifo(pathname, mode)

    if r ~= 0 then
        return err("mkfifo", errno)
    end

    return true
end

local function unlink(pathname)
    local r, errno = l_unlink(pathname)

    if r ~= 0 then
        return err("unlink", errno)
    end

    return true
end

local function rmdir(pathname)
    local r, errno = l_rmdir(pathname)

    if r ~= 0 then
        return err("rmdir", errno)
    end

    return true
end

local function rename(old, new)
    local r, errno = l_rename(old, new)

    if r ~= 0 then
        return err("rename", errno)
    end

    return true
end

--- Network functions.
--- @section net

local function luxio_socket_create(family, socktype)
    socktype = socktype or "tcp" -- default to tcp socket
    local st

    if socktype == "tcp" then
        st = l.SOCK_STREAM
    elseif socktype == "udp" then
        st = l.SOCK_DGRAM
    end

    assert(st ~= nil, "unknown socket type")

    local sock, errno = l_socket(family, st, 0)

    if sock < 0 then
        return err("socket", errno)
    end

    local sockname = ("<socket %s/%s>"):format(
    family == l.AF_INET and "ipv4" or "ipv6", socktype)
    local r = sio_wrap_mt(sock, false, sockname)
    r.sock = { family = family, type = st }

    return r
end

local function inet(socktype)
    return luxio_socket_create(l.AF_INET, socktype)
end

local function inet6(socktype)
    return luxio_socket_create(l.AF_INET6, socktype)
end

local function connect(host, serv)
    serv = tostring(serv)
    assert(type(host) == "string", "host string expected at #1")
    assert(type(serv) == "string", "service string expected at #2")

    local r, addrinfo = l_getaddrinfo(host, serv, 0, l.AF_UNSPEC, l.SOCK_STREAM)
    if r < 0 then
        return nil, ("getaddrinfo: %s"):format(l_gai_strerror(r)), r
    end

    local sock, addr, errno
    for idx, ai in ipairs(addrinfo) do
        sock, errno = l_socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)
        if sock < 0 then
            -- can't create this type of socket
            sock = nil
        else
            r, errno = l_connect(sock, ai.ai_addr)
            if r < 0 then
                -- can't connect to this address
                l_close(sock)
                sock = nil
            else
                -- we connected!
                addr = ai
                break
            end
        end
    end

    if sock == nil then
        -- we couldn't connect, return the last error
        return err("unable to connect", errno)
    end

    local sockname = ("<socket %s/tcp %s %d connected>"):format(
        addr.ai_family == l.AF_INET and "ipv4" or "ipv6",
        addr.ai_addr.address, addr.ai_addr.port)

    r = sio_wrap_mt(sock, false, sockname)
    r.sock = {
        family = addr.ai_family,
        type = addr.ai_socktype,
        addr = addr.ai_addr
    }

    return r
end

local function bind(host, serv, backlog)
    host = host or "::"
    serv = tostring(serv)
    assert(type(serv) == "string", "service string expected at #2")
    backlog = backlog or 32

    local r, addrinfo = l_getaddrinfo(host, serv, l.AI_PASSIVE, l.AF_UNSPEC, l.SOCK_STREAM)
    if r < 0 then
        return nil, ("getaddrinfo: %s"):format(l_gai_strerror(r)), r
    end

    local sock, errno, addr
    for idx, ai in ipairs(addrinfo) do
        sock, errno = l_socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol)
        if sock < 0 then
            -- can't creat this tpe of socket
            sock = nil
        else
            l_setsockopt(sock, l.SOL_SOCKET, l.SO_REUSEADDR, 1)
            r, errno = l_bind(sock, ai.ai_addr)
            if r < 0 then
                -- can't bind to this address
                l_close(sock)
                sock = nil
            else
                -- we bound!
                addr = ai
                break
            end
        end
    end

    if sock == nil then
        -- we couldn't bind, return the last error
        return err("bind", errno)
    end

    r, errno = l_listen(sock, backlog)
    if r < 0 then
        l_close(sock)
        return err("listen", errno)
    end

    local sockname = ("<socket %s/tcp %s %d bound>"):format(
        addr.ai_family == l.AF_INET and "ipv4" or "ipv6",
        addr.ai_addr.address, addr.ai_addr.port)

    r = sio_wrap_mt(sock, false, sockname)
    r.sock = {
        family = addr.ai_family,
        type = addr.ai_socktype,
        addr = addr.ai_addr
    }

    return r
end

local function accept(o)
    sio_check_mt(o)

    local r, addr = l_accept(o.fd)

    if r < 0 then
        return err("accept", addr)
    end

    local sockname = ("<socket %s/tcp %s %d accepted>"):format(
        addr.family == l.AF_INET and "ipv4" or "ipv6",
        addr.address, addr.port)

    r = sio_wrap_mt(r, false, sockname)
    r.sock = {
        family = addr.family,
        type = l.SOCK_STREAM,
        addr = addr
    }

    return r, addr
end

local function msetsockopt(o, level, option, value)
    sio_check_mt(o)
    assert(type(level) == "number", "level number expected at #2")
    assert(type(option) == "number", "option number expected at #3")
    local r, errno = l_setsockopt(o.fd, level, option, value)
    if r == 0 then
        return true
    end

    return err("setsockopt", errno)
end

local function mgetsockopt(o, level, option)
    sio_check_mt(o)
    assert(type(level) == "number", "level number expected at #2")
    assert(type(option) == "number", "option number expected at #3")
    local r, value = l_getsockopt(o.fd, level, option)
    if r == 0 then
        return value
    end

    return err("getsockopt", errno)
end

local function mbind(o, address, port)
    sio_check_mt(o)
    assert(type(address) == "string", "address string expected at #2")
    assert(type(port) == "number", "port number expected at #3")

    local sockaddr = l_make_sockaddr(o.sock.family, port, address)
    local r, errno = l_bind(o.fd, sockaddr)
    if r < 0 then
        return err("bind", errno)
    end

    o.sock.addr = sockaddr
    o.name = ("<socket %s/%s %s %d bound>"):format(
        o.sock.family == l.AF_INET and "ipv4" or "ipv6",
        o.sock.type == l.SOCK_STREAM and "tcp" or "udp",
        sockaddr.address, sockaddr.port)

    return true
end

local function mlisten(o, backlog)
    sio_check_mt(o)
    backlog = backlog or 32
    local r, errno = l_listen(o.fd, backlog)
    if r < 0 then
        return err("listen", errno)
    end

    return true
end

local function mconnect(o, address, port)
    sio_check_mt(o)
    assert(type(address) == "string", "address string expected at #2")
    assert(type(port) == "number", "port number expected at #3")

    local sockaddr = l_make_sockaddr(o.sock.family, port, address)
    local r, errno = l_connect(o.fd, sockaddr)
    if r < 0 then
        return err("connect", errno)
    end

    o.name = ("<socket %s/%s %s %d connected>"):format(
        o.sock.family == l.AF_INET and "ipv4" or "ipv6",
        o.sock.type == l.SOCK_STREAM and "tcp" or "udp",
        sockaddr.address, sockaddr.port)

    return true
end

local function msend(o, buf, f)
    sio_check_mt(o)
    assert(type(buf) == "string")
    f = flags(f or "")
    
    local r, errno = l_send(o.fd, buf, f);
    
    if r < 0 then
        return err("send", errno);
    end
    
    return r
end

local function mrecv(o, count, f)
    sio_check_mt(o)
    assert(type(count) == "number")
    f = flags(f or "")
    
    local r, errno = l_recv(o.fd, count, f);
    
    if r == -1 then
        return err("recv", errno);
    end
    
    return r
end

descriptor_mt = {
    close = close,
    nogc = nogc,
    nonblocking = nonblocking,

    write = write,
    writev = writev,
    read = read,
    seek = seek,
    chmod = fchmod,
    fchmod = fchmod,
    stat = fstat,
    fstat = stat,
    lock = lock,
    locktest = locktest,

    accept = accept,
    setsockopt = msetsockopt,
    getsockopt = mgetsockopt,
    bind = mbind,
    listen = mlisten,
    connect = mconnect,
    send = msend,
    recv = mrecv,

    __tostring = function(x)
        return ("file descriptor: %s (%s)"):format(
        tostring(x.fd or "closed"), x.name or "<unknown>")
    end,

    __gc = sio_meta_gc,
}

descriptor_mt.__index = descriptor_mt

-- Directory enumeration

local lclosedir = l.closedir
local lreaddir = l.readdir

local function dirent_meta_gc(o)
    if not o.closed then
        lclosedir(o.dir)
    end
end

local dirent_wrap_mt
local dirent_check_mt

local dirent_mt = {
    next = function(o)
        dirent_check_mt(o)

        local r, t = lreaddir(o.dir)

        if r == 0 then
            return t -- next directory entry
        elseif r == nil then
            return nil  -- end of directory
        else
            error("readdir iterator: " .. lstrerror(r))
        end
    end,

    iterate = function(o)
        dirent_check_mt(o)

        return function()
            local r, t = lreaddir(o.dir)
            if r == 0 then
                return t.d_name, t
            elseif r == nil then
                -- end of directory
                return nil
            else
                error("readdir iterator: " .. lstrerror(r))
            end
        end
    end,

    close = function(o)
        dirent_check_mt(o)
        lclosedir(o.dir)
        o.closed = true
    end,

    __gc = dirent_meta_gc
}

dirent_mt.__index = dirent_mt

if lua_version == 5.1 then
    dirent_wrap_mt = function(t)
        t.proxy = newproxy(true)
        getmetatable(t.proxy).__gc = function()
            dirent_meta_gc(t)
        end
        return setmetatable(t, dirent_mt)
    end
else
    dirent_wrap_mt = function(t)
        return setmetatable(t, dirent_mt)
    end
end

dirent_check_mt = function(x)
    if getmetatable(x) ~= dirent_mt then
        error "object passed is not a directory object"
    end
    if x.closed then
        error "directory passed has been closed"
    end
end

local lopendir = l.opendir
local function opendir(path)
    local r, errno = lopendir(path)

    if r == nil then
        return err("opendir", errno)
    end

    return dirent_wrap_mt { dir = r }
end

-- Misc helper functions that do not function on descriptors

local lmkdir = l.mkdir
local function mkdir(path, mode)
    mode = sio_mode_flags(mode or "0755")

    if path == "" or path == "/" then
        return true
    end

    local r, errno = lmkdir(path, mode)

    if r < 0 then
        return err("mkdir", errno)
    end

    return r
end

local lfork = l.fork
local function fork()
    local r, errno = lfork()

    if r == -1 then
        return err("fork", errno)
    end

    return r
end

local lexec = l.exec
local function exec(...)
    local r, errno = lexec(...)

    return err("exec", errno)
end

local lexecp = l.execp
local function execp(...)
    local r, errno = lexecp(...)

    return err("execp", errno)
end

local lwaitpid = l.waitpid
local function waitpid(pid, options)
    pid = pid or -1
    options = options or 0
    local r, errno = waitpid(pid, options)

    if r == -1 then
        return err("waitpid", errno)
    end

    return r
end

local l_kill = l.kill
local SIGTERM = l.SIGTERM
local function kill(pid, signal)
    signal = signal or SIGTERM
    if type(pid) ~= "number" or pid < 1 then
        return nil, "invalid pid passed to kill"
    end

    local r, errno = l_kill(pid, signal)
    if r == -1 then
        return err("kill", errno)
    end

    return r
end

local l_setenv = l.setenv
local function setenv(key, value, overwrite)
    local r, errno = l_setenv(key, value, overwrite and 1 or 0)
    if r == -1 then
        return err("setenv", errno)
    end

    return r
end

local l_unsetenv = l.unsetenv
local function unsetenv(key)
    local r, errno = l_unsetenv(key)

    if r == -1 then
        return err("unsetenv", errno)
    end

    return r
end

local l_chdir = l.chdir
local function chdir(path)
    local r, errno = l_chdir(path)
    if r == -1 then
        return err("chdir", errno)
    end

    return r
end

local l_getcwd = l.getcwd
local function getcwd()
    local r, errno = l_getcwd()

    if r == nil then
        return err("getcwd", errno)
    end

    return r
end

return {
    open = open,
    pipe = pipe,
    socketpair = socketpair,
    inet = inet,
    inet6 = inet6,
    connect = connect,
    bind = bind,

    stat = stat,
    lstat = lstat,

    wrap_fd = sio_wrap_mt,
    tomode = sio_mode_flags,
    umask = umask,
    chmod = chmod,
    link = link,
    mkdir = mkdir,
    mkfifo = mkfifo,
    unlink = unlink,
    rmdir = rmdir,
    rename = rename,
    fork = fork,
    exec = exec,
    execp = execp,
    waitpid = waitpid,
    kill = kill,
    setenv = setenv,
    getenv = l.getenv, -- this call cannot fail
    unsetenv = unsetenv,
    opendir = opendir,
    chdir = chdir,
    getcwd = getcwd,

    stdin = sio_wrap_mt(l.STDIN_FILENO, true, "<stdin>"),
    stdout = sio_wrap_mt(l.STDOUT_FILENO, true, "<stdout>"),
    stderr = sio_wrap_mt(l.STDERR_FILENO, true, "<stderr>"),

    luxio = l,
    
    flags = flags,

    _VERSION = "Luxio Simple Interface " .. tostring(l._RELEASE),
    _COPYRIGHT = "Copyright 2012 Rob Kendrick <rjek+luxio@rjek.com>",
    _RELEASE = l._RELEASE
}
