#!/usr/bin/lua

local uci = require('simple-uci').cursor()
local unistd = require 'posix.unistd'
local util = require 'gluon.util'
local site = require 'gluon.site'

-- Returns true if node was offline long enough to perform domain switch
function switch_after_min_reached()
	if not unistd.access("/tmp/gluon_offline") then
		return false
	end

	local switch_after_sec = site.domain_switch.switch_after_offline_mins() * 60

	local current_uptime = util.get_uptime()
	if current_uptime == nil then
		return false
	end

	local f = util.readfile("/tmp/gluon_offline")
	if f == nil then
		return false
	end
	local offline_since = tonumber(f)

	local offline_time_sec = current_uptime - offline_since

	if offline_time_sec > switch_after_sec then
		return true
	end
	return false
end

-- Returns true in case switch time has passed
function switch_time_passed()
	local current_time = os.time()
	local switch_time = site.domain_switch.switch_time()

	return switch_time < current_time
end

if site.domain_switch() == nil then
	-- Switch not applicable for current domain
	print("No domain switch defined for the current domain.")
	os.exit(0)
end

local current_domain = uci:get("gluon", "core", "domain")
local target_domain = site.domain_switch.target_domain()

if target_domain == current_domain then
	-- Current and target domain are equal
	print("Domain '" .. target_domain .. "' equals current domain.")
	os.exit(1)
end

if not switch_after_min_reached() and not switch_time_passed() then
	-- Neither switch-time passed nor switch_after_min reached
	os.exit(0)
end

uci:set("gluon", "core", "domain", target_domain)
uci:commit("gluon")

os.execute("gluon-reconfigure")
os.execute("reboot")