# signature { license=0, seed=277031123, key="01eefa4b906ead41971ac60481a5d074" }
-- ----------------------------------------------------------------------------





require 'paths' 'lms'
require 'permissions'
local sleep = require( 'socket' ).sleep
local lfs = require( 'lfs' )



local dumplog = io.open( 'dumplog.txt', 'w' )
function dump( a, ... )
	if not false then return end

	if a then
		a = tostring( a )
		dumplog:write( a )
		while #a > 0 do
			io.write( a:sub( 1, 80 ) )
			a = a:sub( 81 )
		end
		return dump( ... )
	else
		return print('\n')
	end
end





local logFileName = 'logfile.txt'
function log( ... )
	local a = lfs.attributes( logFileName, 'size' ) or 0
	if 10000 < a then
		local old = 'logfile.old'
		os.remove( old )
		os.rename( logFileName, old )
	end

	local log = io.open( logFileName, 'a+' )
	log:write( os.date( '%Y-%m-%d %H:%M:%S ' ) )
	local args = { ... }
	for i = 1, #args do
		args[ i ] = tostring( args[ i ] )
	end
	log:write ( table.concat( args, ' ' ) )
	log:write ( '\n' )
	log:close()

	print( ... )
end




stopped = false
function stop()
	stopped = true
end




import = function( name )
	local module = require( name )
	package.loaded[ name ] = nil
	return module
end



local run = import





local function testFlag( name )
	local f = io.open( name )
	if not f then return end

	f:close()
	os.remove( name )

	return true
end

log( "InLMS-1.0.3 starting..." )


local f = io.open( 'install.log' )
if f then

	f:close()
else

	CGI = { AUTHORIZATION = 'Basic dGVjaDoxMjM0NTY3OA==' }

	log( "Creating InLMS default configuration" )
	run 'install'


	require 'paths' 'lms'
end


Email = false


local email = io.open( 'email' )
if email then
	Email = email:read( '*a' )
	email:close()
	os.remove( 'email' )
end


OwnIP = false -- luacheck: ignore 131



config = require( 'config' )
cfg = config.load()




i18nTexts = config.read( 'i18n.txt' ).i18n
function i18n( key, default) return i18nTexts[key] or default or key end


log( "InLMS-1.0.3 started." )

if (cfg.DeviceId or '') < ' ' then

	run 'register'
else

	run 'update'
end

if (cfg.DeviceId or '') < ' ' then
	log( i18n("no device ID available, stopping") )
	stop()
end

while not stopped do
	if testFlag( 'loadconfig' ) then
		cfg = config.load()
	end

	_G.immediate = testFlag( 'immediate' )

	if _G.immediate
	or os.time() >= (cfg.nextRequestTime or 0) then
		run 'poll'
	end

	if Email then
		run 'email'
	end


	collectgarbage()


	sleep( 10 )
end

log( "InLMS-1.0.3 stopped." )
