-- lib/supple/track.lua
--
-- Sandbox (for) Untrusted Procedure Partitioning (in) Lua Engine
--
-- Tracking and logging for debug porpoises.
--
-- Copyright 2012 Daniel Silverstone <dsilvers@digital-scurf.org>
--
-- For licence terms, see COPYING
--

---
-- Communications tracking for Supple sandboxes.
--
-- This module provides a mechanism for keeping track of what goes on in the
-- communications path of a sandboxed runtime.  The track is held from the
-- point of view of whichever side caused it to be recorded (typically the
-- host).  Tracks are best generated by ensuring tracking is enabled and then
-- calling `supple.host.run`.  Retrieval of the track afterwards is then
-- simple.
--
--     supple.track.start()
--     supple.host.run(....)
--     print("Track:\n" .. supple.track.stop())
--


local depth
local track

local function record(...)
   if depth then
      track[#track+1] = { depth, ... }
   end
end

local function enter(...)
   if depth then
      record(">>>", ...)
      depth = depth + 1
   end
end

local function leave(...)
   if depth then
      if depth > 0 then
	 depth = depth - 1
      end
      record("<<<", ...)
   end
end

---
-- Clear the track data and begin tracking.
--
-- Call this routine to clear the current track data and begin tracking comms
-- and other Supple internals.
--
-- @function start

local function start_tracking()
   depth, track = 0, {}
end

---
-- Stop tracking and return the current track.
--
-- Assuming you have started tracking with `supple.track.start` you can call
-- this function to stop tracking and retrieve the track as a string.
--
-- @treturn string The track data
-- @function stop

local function stop_tracking()
   if track == nil then
      return "***NO TRACKING DATA***"
   end
   local ret = {}
   for i = 1, #track do
      local ent = track[i]
      local pfx = ("  "):rep(ent[1])
      table.remove(ent, 1)
      ret[#ret+1] = pfx .. table.concat(ent, " ")
   end
   depth, track = nil, {}
   return table.concat(ret, "\n")
end

return {
   start = start_tracking,
   stop = stop_tracking,
   enter = enter,
   leave = leave,
   record = record,
}
