jail = {}
local storage = minetest.get_mod_storage()

function release_prisoners(name)
   local player = minetest.get_player_by_name(name)
   if not player then
      return
   end
   minetest.chat_send_player(name, '<Jail Staff> We hope you enjoyed your stay.')
   minetest.set_player_privs(name, {shout=true, home=true})
   player:setpos({x=2555, y=2002, z=4442})
   minetest.log('action', name..' was freed from jail')
   storage:set_string(name, '')
   storage:set_string(name..'_length', '')
   minetest.show_formspec(name, 'rules', spawn_rules_formspec)
end

minetest.register_privilege('warden', {
   description = 'Can send people to jail',
   give_to_singleplayer = false
})

minetest.register_chatcommand('release', {
   params = '<name>',
   privs = {warden=true},
   func = function(warden, name)
      release_prisoners(name)
   end,
})

minetest.register_chatcommand('jail', {
   params = '<name> [<time>] [<reason>]',
   description = 'Send player to jail.',
   privs = {warden=true},
   func = function(warden, param)
      local params = param:split(',')
      local name = params[1]
      local time = params[2] or 300
      local reason = params[3] or 'reasons'
      local player = minetest.get_player_by_name(name)
      if not player then
         minetest.chat_send_player(warden, 'That player is not here!')
         return
      end
      minetest.log('action', name..' was jailed by '..warden)
      minetest.set_player_privs(name, {shout=true}) --revoke all privs but shout
      local jail_cells = { --locations of the cells that players can be placed in.
         {x=2562, y=2001, z=4438},
         {x=2562, y=2001, z=4442},
         {x=2562, y=2001, z=4446},
      }
      local cell_loc = jail_cells[math.random(3)]
      local sign_loc = {x = cell_loc.x-3, y = cell_loc.y+3, z = cell_loc.z}
      player:setpos(cell_loc)
      minetest.chat_send_player(name, 'You were sent to jail for '..time..' seconds for '..reason..'.')
      storage:set_string(name, 'jailed')
      storage:set_string(name..'_length', time)
      local meta = minetest.get_meta(sign_loc)
      meta:set_string('text', reason)
      meta:set_string('infotext', reason)
      minetest.after(time, function()
         release_prisoners(name)
      end)
   end,
})

minetest.register_on_joinplayer(function(player)
   local name = player:get_player_name()
   local jailed = storage:get_string(name)
   if jailed == 'jailed' then
      local time = tonumber(storage:get_string(name..'_length'))
      minetest.chat_send_player(name, 'So you thought you could evade serving your time? You have '..time..' seconds to serve')
      minetest.after(time, function()
         release_prisoners(name)
      end)
   end
end)
