local args={...}
local drivers=args[1]
local log=args[2]
local bootDisk=args[3]
local driverutil=args[4]
local wd="/"
log.api.log("Bootdrive is "..bootDisk)
if not drivers.disk then
    error("WTF") -- ???
end

local disks={}
local mounts={
    ["/"]=bootDisk
}
local meta={}

local function refreshDisks()
    local diskstmp={}
    local tmp={}
    for i,v in driverutil.list("disk") do
        tmp[#tmp+1] = v
    end
    for _,d in ipairs(tmp) do
        for i,v in d.api.list() do
            if diskstmp[i]==nil then
                diskstmp[i]=v
            end
        end
    end
    disks=diskstmp
end
refreshDisks()
--[[
meta=load("return "..(disks[bootDisk].readAllText("/sys/fs/meta.ltn") or "{}"), "meta")()
if not meta then error("Meta failed to load") end
]]
local function resolve(path)
    if path:sub(1,1)~="/" then path=wd..path end
    local currmatch="/"
    for i,_ in pairs(mounts) do
        if string.hasPrefix(path, i) then
            if #i>#currmatch then
                currmatch=i
            end
        end
    end
    local drive=disks[mounts[currmatch]]
    local newPath=string.getSuffix(path, currmatch)
    return drive, newPath
end

local fs={}

function fs.list(path)
    local drive, newPath = resolve(path)
    return drive.list(newPath)
end

function fs.readAllText(path)
    local drive, newPath = resolve(path)
    return drive.readAllText(newPath)
end

function fs.writeAllText(path, content)
    local drive, newPath = resolve(path)
    return drive.writeAllText(newPath, content)
end

function fs.delete(path)
    local drive, newPath = resolve(path)
    return drive.delete(newPath)
end

function fs.exists(path)
    local drive, newPath = resolve(path)
    return (drive.fileExists(newPath) or drive.directoryExists(newPath))
end

function fs.fileExists(path)
    local drive, newPath = resolve(path)
    return drive.fileExists(newPath)
end

function fs.directoryExists(path)
    local drive, newPath = resolve(path)
    return drive.directoryExists(newPath)
end

function fs.createFile(path)
    local drive, newPath = resolve(path)
    return drive.makeFile(newPath)
end

function fs.createDirectory(path)
    local drive, newPath = resolve(path)
    return drive.makeDirectory(newPath)
end

fs.mkDir=fs.createDirectory
fs.mkFile=fs.createFile
fs.isDir=fs.directoryExists
fs.isFile=fs.fileExists

function fs.getWorkingDir()
    return wd
end

function fs.setWorkingDir(dir)
    if type(dir)~="string" then error("Invailid path") end
    if dir:sub(1,1)~="/" then dir=wd..dir end
    if dir:sub(#dir,#dir)~="/" then dir=dir.."/" end
    if not fs.isDir(dir) then error("Invailid path") end
end

function fs.loadAsFunc(path)
    local file = fs.readAllText(path)
    return load(file, path, "t", setmetatable({},{
        __index=_G,
        __metatable=false
    }))
end

return fs