--[[
Copyright (c) 2012-2015 Kaarle Ritvanen
See LICENSE file for license details
--]]

--- @module aconf.model

local fld = require('aconf.model.field')
local new = require('aconf.model.model').new
local super = require('aconf.object').super
local pth = require('aconf.path')
local store = require('aconf.persistence')

--- create a model corresponding to an OpenRC service.
-- @function service
-- @tparam string name name of the service
-- @return (<i>[&lt;Model&gt;](#new)</i>) new model which has two pre-defined
-- boolean fields, *enabled* and *status*, for controlling the
-- service's lifecycle and inspecting its current status.
return function(name)
	  local res = new()

	  local addr = pth.join('/service', name)
	  local eaddr = pth.join(addr, 'enabled')
	  res.enabled = fld.Boolean{addr=eaddr, required=true}
	  res.status = fld.String{addr=pth.join(addr, 'status'), editable=false}

	  local function is_enabled() return store:get(eaddr) end
	  local enabled
	  local function pre() enabled = is_enabled() end
	  local function post()
	     if enabled and is_enabled() then
		os.execute('rc-service '..name..' reload')
	     end
	  end

	  function res:init(context)
	     store:trigger('pre', context.addr, pre)
	     store:trigger('post', context.addr, post)
	     super(self, res):init(context)
	  end

	  return res
       end
