-- Settings 2.0 by nothy
-- (C) Linus Ramneborg 2018
local tutils = textutils
variables = {
  temp = {
    currentUser = nil,
    last_update = "Never",
    last_updatecheck = "Never",
    first_start = true,
    updatemode = "",
    api_dir = "/home/APIs/",
    first_update = false,

  },
  users = {
    ["KERNEL"] = {
      password = ".",
      superuser = true,
      displayName = "Kernel",
      lastlogin = "Never",
      background = "default.axg",
      allow_apis = false,
      system_skipsys_scan = false,
      system_skip_error = false,
      fexplore_startdir = "/home/",
    },
  },
  terminalCommands = {
    testcommand = {
      code = [[term.setTextColor(colors.green)
      write('This is an example custom command.\nA command manager is coming in the future.\n')
      term.setTextColor(colors.white)]]
    },
  },
}

function loadsettings(dir)
  if fs.exists(dir) then
    local unserial = fs.open(dir,"r")
    variables = textutils.unserialize(unserial.readAll())
    unserial.close()
    return variables
  else
    error("file not present",2)
    return nil
  end
end
function getVariable(a,b)
  --print("setting.getVariable(a,b) is a deprecated function! use setting.variables.<whatever variable you're looking at>.")
  return "deprecated"
end
function setVariable(a,b,c)

end
function getSettings()
  return variables
end
function setSettings(var)
  if type(var) == "table" then
    variables = var
  else
    error("expected table, got "..type(var),2)
  end
end
function getUsers()
  return variables.users
end
function writesettings()
  local vars = variables
  --print(textutils.serialise(vars))
  local serial = tutils.serialise(vars)

  --print(serial)
  local fh = fs.open("Axiom/settings.bak","w")
  fh.write(serial)
  fh.close()
end


function addUser(username, pw, display,su)
  if su == nil then su = false end
  variables.users[tostring(username)] = {
    password = pw,
    displayName = display,
    superuser = su,
    lastlogin = "Just now",
    background = "default.nfp",
    allow_apis = false,
    system_skipsys_scan = false,
    system_skip_error = false,
    fexplore_startdir = "/home/",
    allow_downloads = true,
  }
end
function deleteUser(username)
  loadsettings("Axiom/settings.bak")
  for k, v in pairs(variables.users) do
    if k == username or v.displayName == username then 
      variables.users[k] = nil
      break
    end
  end
  writesettings()
end
if fs.exists("Axiom/settings.bak") then
  loadsettings("Axiom/settings.bak")
elseif fs.exists("Axiom/settings.bak") then
  fs.copy("Axiom/settings.0","Axiom/settings.bak")
  fs.delete("Axiom/settings.0")
  loadsettings("Axiom/settings.bak")
end
