DROP PROCEDURE IF EXISTS account.role_sync;

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `account`.`role_sync`()
BEGIN
/**
 * Synchronize the @roleRole table with the current role hierarchy. This
 * procedure must be called every time the @roleInherit table is modified so
 * that the changes made on it are effective.
 */
	DECLARE vRoleId INT;
	DECLARE vDone BOOL;

	DECLARE cur CURSOR FOR
		SELECT id FROM role;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	DROP TEMPORARY TABLE IF EXISTS tRoleRole;
	CREATE TEMPORARY TABLE tRoleRole
		ENGINE = MEMORY
		SELECT * FROM roleRole LIMIT 0;

	OPEN cur;

	l: LOOP
		SET vDone = FALSE;
		FETCH cur INTO vRoleId;

		IF vDone THEN
			LEAVE l;
		END IF;

		CALL role_getDescendents(vRoleId);

		INSERT INTO tRoleRole (role, inheritsFrom)
			SELECT vRoleId, id FROM tmp.role;

		DROP TEMPORARY TABLE tmp.role;
	END LOOP;

	CLOSE cur;

	START TRANSACTION;
	DELETE FROM roleRole;
	INSERT INTO roleRole SELECT * FROM tRoleRole;
	COMMIT;

	DROP TEMPORARY TABLE tRoleRole;

	CALL role_syncPrivileges;
END$$
DELIMITER ;
