﻿-- 3241

-------------------------------------------------------------------------------
--
-- [dbo].[Temp.UpgradeSureBackupRoles]
--
-------------------------------------------------------------------------------
PRINT 'Creating [dbo].[Temp.UpgradeSureBackupRoles]'
	EXEC [dbo].[System.DeleteFunction] '[dbo].[Temp.UpgradeSureBackupRoles]'
GO

	CREATE FUNCTION [dbo].[Temp.UpgradeSureBackupRoles] (
		@xml as xml)
	RETURNS xml
	AS 
	BEGIN	
		DECLARE @domain_controller_id as uniqueidentifier = '{D307CA96-4CA6-42D1-8FE7-16B03700E222}'
		DECLARE @global_catalog_id as uniqueidentifier = '{970E86CA-33BB-4D46-9093-2E1A114A818B}'
		DECLARE @domain_controller_authoritative as nvarchar(255) = 'Domain Controller (Authoritative Restore)'
		DECLARE @domain_controller as nvarchar(255) = 'Domain Controller'
		DECLARE @active_directory as nvarchar(255) = 'Active Directory'

		DECLARE @sb_roles_table as table ( 
			[id] nvarchar(255) NOT NULL,
			[name] nvarchar(max) NOT NULL,
			[application_name] nvarchar(max) NOT NULL)

		INSERT INTO @sb_roles_table
		SELECT 
--			T.x.value('for $a in . return count($a/../*[. << $a]) + 1', 'int') as [index],
--			T.x.value('(./SbRole/Id/text())[1]', 'uniqueidentifier') as [id],
			T.x.value('(./SbRole/Id/text())[1]', 'nvarchar(max)') as [id],
			T.x.value('(./SbRole/Name/text())[1]', 'nvarchar(max)') as [name],
			T.x.value('(./SbRole/ApplicationName/text())[1]', 'nvarchar(max)') as [application_name]
		FROM
			@xml.nodes('/SbObjectOptions/Roles/SbRoles/Role') T(x)

		UPDATE
			@sb_roles_table
		SET
			[name] = @domain_controller_authoritative
		WHERE
			cast([id] as uniqueidentifier) = @domain_controller_id AND [name] LIKE @domain_controller

		DECLARE @result as bigint = @@rowcount

		IF EXISTS (SELECT * FROM @sb_roles_table WHERE cast([id] as uniqueidentifier) = @global_catalog_id)
		BEGIN
			IF NOT EXISTS (SELECT * FROM @sb_roles_table WHERE cast([id] as uniqueidentifier) = @domain_controller_id)
			BEGIN
				INSERT INTO @sb_roles_table
					([id], [name], [application_name])
				VALUES
					(lower(cast(@domain_controller_id as nvarchar(255))), @domain_controller_authoritative, @active_directory)

				SET @result = @result + 1
			END
		END

		IF @result > 0
		BEGIN
			SET @xml.modify('delete /SbObjectOptions/Roles/SbRoles/*')

			DECLARE @sb_roles as xml = 
			(
				SELECT 
					[id] as 'SbRole/Id',
					[name] as 'SbRole/Name',
					[application_name] as 'SbRole/ApplicationName'
				FROM
					@sb_roles_table FOR XML PATH('Role')
			)

			SET @xml.modify('insert sql:variable("@sb_roles") as last into (/SbObjectOptions/Roles/SbRoles)[1]')

			RETURN @xml
		END

		RETURN NULL
	END
GO


--------------------------------------------------------------------------------
--
-- Begin Upgrade
--
--------------------------------------------------------------------------------
SET NOCOUNT ON

DECLARE @db_version int
SET @db_version = (SELECT max([current_version]) FROM [dbo].[Version])

PRINT ''
PRINT 'Begin database upgrade...'
PRINT [dbo].[System.FormatString]('\t[Time Stamp]="%s"', convert(varchar, getdate(), 113))
PRINT [dbo].[System.FormatString]('\t[Database Version]="%s"', @db_version)
PRINT [dbo].[System.FormatString]('\t[Server Name]="%s"', @@servername)
PRINT [dbo].[System.FormatString]('\t[Process ID]="%s"', @@spid)
PRINT [dbo].[System.FormatString]('\t[User Name]="%s"', SYSTEM_USER)
PRINT ''

GO


--------------------------------------------------------------------------------
--
-- [dbo].[ObjectsInApplicationGroups]
--
--------------------------------------------------------------------------------
PRINT 'Begin upgrading SureBackup roles in [dbo].[ObjectsInApplicationGroups]'

DECLARE @count int
SET @count = 0

DECLARE options_table_cursor CURSOR FOR	SELECT [id], [options] FROM [dbo].[ObjectsInApplicationGroups]

OPEN options_table_cursor

DECLARE @id uniqueidentifier
DECLARE @options xml

FETCH NEXT FROM options_table_cursor INTO @id, @options

WHILE @@fetch_status = 0
BEGIN
	DECLARE @upgraded_options as xml = [dbo].[Temp.UpgradeSureBackupRoles](@options)

	IF @upgraded_options IS NOT NULL
	BEGIN
		PRINT [dbo].[System.TransformCppText]('BEGIN ITERATION')

		PRINT [dbo].[System.FormatString]('\t[Id]="%s"', @id)
		PRINT [dbo].[System.TransformCppText]('\t[Options]=>>>')
		PRINT [dbo].[System.FormatXmlDocument](@options, 2, DEFAULT)
		PRINT [dbo].[System.TransformCppText]('\t[Options]=<<<')
		PRINT [dbo].[System.FormatXmlDocument](@upgraded_options, 2, DEFAULT)

		UPDATE
			[dbo].[ObjectsInApplicationGroups]
		SET
			[options] = @upgraded_options
		WHERE CURRENT OF
			options_table_cursor

		PRINT [dbo].[System.TransformCppText]('END ITERATION')

		SET @count = @count + 1
	END

	FETCH NEXT FROM options_table_cursor INTO @id, @options
END

CLOSE options_table_cursor
DEALLOCATE options_table_cursor

PRINT 'End upgrading SureBackup roles in [dbo].[ObjectsInApplicationGroups]'
PRINT [dbo].[System.FormatString]('\t[Roles Count]="%s"', @count)
PRINT ''
GO


--------------------------------------------------------------------------------
--
-- [dbo].[SbVerificationRules]
--
--------------------------------------------------------------------------------
PRINT 'Begin upgrading SureBackup roles in [dbo].[SbVerificationRules]'

DECLARE @count int
SET @count = 0

DECLARE options_table_cursor CURSOR FOR	SELECT [id], [options] FROM [dbo].[SbVerificationRules]

OPEN options_table_cursor

DECLARE @id uniqueidentifier
DECLARE @options xml

FETCH NEXT FROM options_table_cursor INTO @id, @options

WHILE @@fetch_status = 0
BEGIN
	DECLARE @upgraded_options as xml = [dbo].[Temp.UpgradeSureBackupRoles](@options)

	IF @upgraded_options IS NOT NULL
	BEGIN
		PRINT [dbo].[System.TransformCppText]('BEGIN ITERATION')

		PRINT [dbo].[System.FormatString]('\t[Id]="%s"', @id)
		PRINT [dbo].[System.TransformCppText]('\t[Options]=>>>')
		PRINT [dbo].[System.FormatXmlDocument](@options, 2, DEFAULT)
		PRINT [dbo].[System.TransformCppText]('\t[Options]=<<<')
		PRINT [dbo].[System.FormatXmlDocument](@upgraded_options, 2, DEFAULT)

		UPDATE
			[dbo].[SbVerificationRules]
		SET
			[options] = @upgraded_options
		WHERE CURRENT OF
			options_table_cursor

		PRINT [dbo].[System.TransformCppText]('END ITERATION')

		SET @count = @count + 1
	END

	FETCH NEXT FROM options_table_cursor INTO @id, @options
END

CLOSE options_table_cursor
DEALLOCATE options_table_cursor

PRINT 'End upgrading SureBackup roles in [dbo].[SbVerificationRules]'
PRINT [dbo].[System.FormatString]('\t[Roles Count]="%s"', @count)
PRINT ''
GO


--------------------------------------------------------------------------------
--
-- End Upgrade
--
--------------------------------------------------------------------------------
PRINT 'Deleting [dbo].[Temp.UpgradeSureBackupRoles]'
EXEC [dbo].[System.DeleteFunction] '[dbo].[Temp.UpgradeSureBackupRoles]'

PRINT ''
PRINT 'Finishing database upgrade...'
PRINT [dbo].[System.FormatString]('\t[Total Read]="%s"', @@total_read)
PRINT [dbo].[System.FormatString]('\t[Total Write]="%s"', @@total_write)
PRINT [dbo].[System.FormatString]('\t[Total Errors]="%s"', @@total_errors)
PRINT [dbo].[System.FormatString]('\t[End Date]="%s"', convert(varchar, getdate(), 113))
PRINT ''
GO
