-- Crispy's Flexible initialization system.

cfis_root_path = "/"
cfis_script_path = shell.getRunningProgram()
if cfis_script_path:match("^/disk") ~= nil then
	cfis_root_path = "/disk/"
end

cfis_base_path = cfis_root_path .. "c"
if not fs.isDir(cfis_base_path) then
	fs.makeDir(cfis_base_path)
end
cfis_base_path = cfis_base_path .. "/"

if os.getComputerLabel() == nil and not fs.exists("/nolabel") then
	print("This computer has no label.  Enter a label and press enter, or leave blank for no label.")
	newLabel = io.read()
	if newLabel ~= nil and newLabel:len() > 0 then
		os.setComputerLabel(newLabel)
		print("Label set.")
	else
		print("No label set.")
	end
end

if os.getComputerLabel() ~= nil then
	print("I am: " .. os.getComputerLabel() .. " (" .. os.getComputerID() .. ")")
else
	print("I am: #" .. os.getComputerID())
end


if not fs.isDir(cfis_base_path .. "apis") then
	fs.makeDir(cfis_base_path .. "apis")
end

if not fs.isDir(cfis_base_path .. "startup") then
	fs.makeDir(cfis_base_path .. "startup")
end

if not fs.isDir(cfis_base_path .. "apps") then
	fs.makeDir(cfis_base_path .. "apps")
end

for apiIdx, apiName in ipairs(fs.list(cfis_base_path .. "apis")) do
	os.loadAPI(cfis_base_path .. "apis/" .. apiName)
end

for startupIdx, startupName in ipairs(fs.list(cfis_base_path .. "startup")) do
	shell.run(cfis_base_path .. "startup/" .. startupName)
end

function smartCopy(fromPath, toPath)
	if fromPath ~= "/" and fromPath:match("/$") ~= nil then fromPath = fromPath:sub(1, fromPath:len() - 1) end
	if toPath ~= "/" and toPath:match("/$") ~= nil then toPath = toPath:sub(1, toPath:len() - 1) end
	if not fs.exists(fromPath) then return false end
	if fs.isDir(fromPath) then
		if fromPath ~= "/" then fromPath = fromPath .. "/" end
		if fs.exists(toPath) then
			if fs.isDir(toPath) then
				if toPath ~= "/" then toPath = toPath .. "/" end
				local fileIdx
				for fileIdx, fileName in ipairs(fs.list(fromPath)) do
					smartCopy(fromPath .. fileName, toPath .. fileName)
				end
			else
				fs.delete(toPath)
				if toPath ~= "/" then toPath = toPath .. "/" end
				fs.copy(fromPath, toPath)
			end
		else
			fs.copy(fromPath, toPath)
		end
	else
		if fs.exists(toPath) then fs.delete(toPath) end
		fs.copy(fromPath, toPath)
	end
end

function askQuestion(str)
	print(str .. " (y/n)")
	local res = io.read()
	res = res:lower()
	if res == "y" or res == "yes" or res == "true" then return true end
	return false
end

if fs.isDir("/disk") and fs.isDir("/disk/install") and not fs.exists("/noinstall") then
	if askQuestion("Install files found on disk.  Do you want to install them?") then
		print("Installing ...")
		smartCopy("/disk/install/", "/")
		print("Done installing.")
	else
		print("Install aborted.")
	end
end


