local chrooted=false
local chrootpath=""
local chrootpass=nil
local fscombine=fs.combine
local rootfs = {}

for k,v in pairs(fs) do
  rootfs[k] = v
end

function chroot(path, pass)
if chrooted then
error("Cannot chroot from pre-existing chroot enviroment without unchrooting")
end
if not pass then
chrootpass=nil
else
chrootpass=pass
end
if fs.isDir(path) then
chrootpath=rootfs.combine("", path)
chrooted=true
else
error("Could not find chroot path or is not a directory")
end
end
function unchroot(pass)
if chrooted then
if chrootpass==pass then
chrooted=false
chrootpath=""
return true
else
error("Pass incorrect")
end
else
error("Not chrooted.")
end
end
function isChrooted()
return chrooted
end
--From lua users wiki
local function starts(String,Start)
   return string.sub(String,1,string.len(Start))==Start
end
--BEGIN
local function valid(path)
	if starts(fscombine("", path), "rom") then
		return path
	end
	local xpath=fscombine(chrootpath, path)
	if starts(xpath, chrootpath) then
		return xpath
	else
		error("No escaping the chroot jail! The xpath is "..xpath)
	end
end

local function root(path)
	if fscombine(chrootpath, "") == fscombine(path, "") then
		return true
	end
end

fs.list=function(path)
	if root(valid(path)) then
		local list = rootfs.list(valid(path))
		table.insert(list, "rom")
		return list
	else
		return rootfs.list(valid(path))
	end
end

fs.exists=function(path)
	return rootfs.exists(valid(path))
end
fs.isDir=function(path)
	return rootfs.isDir(valid(path))
end
fs.isReadOnly=function(path)
	return rootfs.isReadOnly(valid(path))
end
fs.getDrive=function(path)
	return rootfs.getDrive(valid(path))
end
fs.getSize=function(path)
	return rootfs.getSize(chrootpath..path)
end
fs.makeDir=function(path)
	return rootfs.makeDir(valid(path))
end
fs.move=function(path, cpath)
	return rootfs.move(valid(path), valid(cpath))
end
fs.copy=function(path, cpath)
	return rootfs.copy(valid(path), valid(cpath))
end
fs.delete=function(path)
	return rootfs.delete(valid(path))
end
fs.open=function(path, m)
	return rootfs.open(valid(path), m)
end

fs.secret=function()
	local longtimeago=rootfs.open("/rom/programs/secret/alongtimeago","r")
	local prog=loadstring(longtimeago.readAll())
	longtimeago.close()
	return prog
end