#!/usr/bin/lua
--
--  rhnop
--
--  Copyright (C) 2011-2015 Christian Pointner <equinox@helsinki.at>
--
--  This file is part of rhnop.
--
--  rhnop is free software: you can redistribute it and/or modify
--  it under the terms of the GNU General Public License as published by
--  the Free Software Foundation, either version 3 of the License, or
--  any later version.
--
--  rhnop is distributed in the hope that it will be useful,
--  but WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--  GNU General Public License for more details.
--
--  You should have received a copy of the GNU General Public License
--  along with rhnop. If not, see <http://www.gnu.org/licenses/>.
--

socket = require "socket"

package.path = package.path .. ";_rhnoplibdir_/?.lua"
db = require "db"
conf = require "conf"

local cnf = conf.load("_rhnopescdir_/nopsysstated.conf")

db = assert(db.init(cnf.db_db, cnf.db_user, cnf.db_pwd, cnf.db_host, cnf.db_port, cnf.db_table))

local sock = assert(socket.tcp())
local ret, err = sock:connect(cnf.host, cnf.port)
if ret == nil then
   print(err)
   return 1
end
print "connection established"

local current_state, err = db:getLastSysState()
if current_state == nil then
   print(err)
   return 1
end
print("current state according to db is " .. current_state)

while true do
   local state = sock:receive('*l')
   if state == nil then break end
   if state ~= current_state then
      -- reading timestamp (milliseconds since epoch)
      local p = assert(io.popen("/bin/date --utc '+%s %N'" , 'r'))
      local time = assert(p:read('*l'))
      p:close()
      local s, ns = assert(string.match(time, "([0-9]+) ([0-9]+)"))
      local timestamp = s .. string.format("%06d", math.floor(ns/1000))

      assert(db:updateSysState(timestamp, state))
      current_state = state
   end
end

sock:close()

return 0