-- LegacyWorlds Beta 6
-- PostgreSQL database scripts
--
-- System status functions
--
-- Copyright(C) 2004-2010, DeepClone Development
-- --------------------------------------------------------


--
-- Enter maintenance mode
--
-- Parameters:
--	a_id		Administrator identifier
--	reason_txt	Maintenance reason
--	duration	Expected duration (minutes)
--
-- Returns:
--	success		TRUE on success, FALSE if the system was already in maintenance mode
--

CREATE OR REPLACE FUNCTION sys.enter_maintenance_mode( IN a_id INT , IN reason_txt TEXT , IN duration INT , OUT success BOOLEAN )
		STRICT VOLATILE
		SECURITY DEFINER
	AS $$
BEGIN
	UPDATE sys.status
		SET maintenance_start = NOW( ) ,
			maintenance_end = NOW( ) + ( duration || 'm' )::INTERVAL ,
			maintenance_text = reason_txt
		WHERE maintenance_start IS NULL;
	success := FOUND;
	IF success
	THEN
		PERFORM admin.write_log( a_id , 'WARNING'::log_level , 'enabled maintenance mode for ' ||
			duration || ' minutes; reason: ' || reason_txt );
	END IF;
END;
$$ LANGUAGE plpgsql;

GRANT EXECUTE ON FUNCTION sys.enter_maintenance_mode( INT , TEXT , INT ) TO :dbuser;



--
-- Extend maintenance mode duration
--
-- Parameters:
--	a_id			Administrator identifier
--	ext_duration	Expected extended duration (minutes)
--
-- Returns:
--	success		TRUE on success, FALSE if the system was not in maintenance mode
--

CREATE OR REPLACE FUNCTION sys.extend_maintenance_mode( IN a_id INT , IN ext_duration INT , OUT success BOOLEAN )
		STRICT VOLATILE
		SECURITY DEFINER
	AS $$
BEGIN
	UPDATE sys.status
		SET maintenance_end = NOW( ) + ( ext_duration || 'm' )::INTERVAL
		WHERE maintenance_start IS NOT NULL;
	success := FOUND;
	IF success
	THEN
		PERFORM admin.write_log( a_id , 'WARNING'::log_level , 'extended maintenance mode duration by ' ||
			ext_duration || ' minutes' );
	END IF;
END;
$$ LANGUAGE plpgsql;

GRANT EXECUTE ON FUNCTION sys.extend_maintenance_mode( INT , INT ) TO :dbuser;




--
-- Exit maintenance mode
--
-- Parameters:
--	a_id		Administrator identifier
--
-- Returns:
--	success		TRUE on success, FALSE if the system was not in maintenance mode
--

CREATE OR REPLACE FUNCTION sys.exit_maintenance_mode( IN a_id INT , OUT success BOOLEAN )
		STRICT VOLATILE
		SECURITY DEFINER
	AS $$
BEGIN
	UPDATE sys.status
		SET maintenance_start = NULL ,
			maintenance_end = NULL ,
			maintenance_text = NULL
		WHERE maintenance_start IS NOT NULL;
	success := FOUND;
	IF success
	THEN
		PERFORM admin.write_log( a_id , 'INFO'::log_level , 'terminated maintenance mode' );
	END IF;
END;
$$ LANGUAGE plpgsql;

GRANT EXECUTE ON FUNCTION sys.exit_maintenance_mode( INT ) TO :dbuser;

