local l = require "luxio"

function check(r, e, ...)
   if r < 0 then
      error(l.strerror(r))
   end
   return r, e, ...
end

r, w = 1, 2
pipe = {}
check(l.pipe(pipe))

pr = pipe[1]
pw = pipe[2]

-- discover pipe read/write size to use
local pz = 64 * 1024
if l.F_GETPIPE_SZ then
   local ppz = check(l.fcntl(pipe[w], l.F_GETPIPE_SZ))
   if ppz > pz then pz = ppz end
end

r, in_stat = l.stat(arg[1])
if r == -1 then error "unable to stat input file" end


in_file = check(l.open(arg[1], l.O_RDONLY))
out_file = check(l.open(arg[2], l.bit.bor(l.O_CREAT, l.O_WRONLY), in_stat.mode))

repeat
   r = l.splice(in_file, nil, pw, nil, pz, l.SPLICE_F_MORE)
   if r > 0 then
      l.splice(pr, nil, out_file, nil, pz, l.SPLICE_F_MORE)
   end
until r == 0

l.fdatasync(out_file)

l.close(pr)
l.close(pw)
l.close(out_file)
l.close(in_file)

os.exit()
