DROP PROCEDURE IF EXISTS bustCache;

DELIMITER //

CREATE PROCEDURE bustCache(IN assetFilename VARCHAR(255), IN email VARCHAR(255), IN comment TEXT, OUT success TINYINT(1))
BEGIN
	# Get Site ID
	select id into @siteId from site limit 1;

	# Get user ID of the person busting the cache
	select id into @userId from user where email_address = email;

	# Get the ID of the file to bust
	select id into @assetId from cache_asset where filename = assetFilename limit 1;

	# Get the next version of the file to bust.
	select max(version) + 1 into @newVersion from cache_history where cache_asset_id = @assetId;


	# There may not be any history.
	if (@newVersion IS NULL) then
		set @newVersion = 1;
	end if;

	# Bust the cache.
	insert into `cache_history` (`cache_asset_id`, `site_id`, `user_id`, `bust_when`, `version`, `reason`)
	values (@assetId, @siteId, @userId, now(), @newVersion, comment);

	select ROW_COUNT() into success;
END //

DELIMITER ;