-------------
-- ROLES
-------------
	USE [IHBoxSystem]
	GO
	CREATE ROLE opcua_read AUTHORIZATION dbo 
	GO  

	USE [IHBoxSystem]
	GO
	CREATE ROLE opcua_write AUTHORIZATION dbo 
	GO  

	USE [IHBoxSystem]
	GO
	EXEC sp_addrolemember 'opcua_read', 'admin'
	GO

	USE [IHBoxSystem]
	GO
	EXEC sp_addrolemember 'opcua_read', 'SDI/australtek'
	GO

	USE [IHBoxSystem]
	GO
	EXEC sp_addrolemember 'opcua_write', 'SDI/australtek'
	GO

	USE [IHBoxSystem]
	GO
	EXEC sp_addrolemember 'opcua_write', 'admin'
	GO

-------------------
-- Menu and Route
-------------------
	declare @parent int, @result_routeId INT
	-- Try to find existing "OPC" or "Tools" menu, otherwise use root
	select @parent=id from [FrontEnd].[Menu] where [Name] = 'OPC' and Parent is null
	if @parent is null
		select @parent=id from [FrontEnd].[Menu] where [Name] = 'Tools' and Parent is null
	if @parent is null
		select @parent=id from [FrontEnd].[Menu] where Parent is null and [Name] = 'MES' -- fallback to MES section
    -- If no parent found, set to NULL for root level
    if @parent is null
        set @parent = null

	INSERT INTO [FrontEnd].[Routes]
			   ([Route]
			   ,[ModuleName]
			   ,[ModulePath]
			   ,[RequiredRole]
		   )
		 VALUES 
			   (
			   '!/opcua-browser(/)'
			   , 'opcua-browser'
			   , 'pages/opcua/opcua-browser/'
			   , 'opcua_read'           
			   )
			   SET @result_routeId = @@IDENTITY
	INSERT INTO [FrontEnd].[Menu]
			   ([Parent]
			   ,[Name]
			   ,[RouteID]
			   ,[SortOrder]
			   ,[Enabled]
			   ,[Visible]
			   ,[RequiredRole]
			   ,[Group]
			  )
		 VALUES
			   (
			   @parent
			   ,'OPC UA Browser'
			   ,@result_routeId 
			   ,1
			   ,1
			   ,1
			   ,'opcua_read'
			   ,NULL
			 )
	GO


-------------------
--	Profiles
-------------------
	USE [IHBoxSystem]
	GO

	DECLARE @ModuleId INT

	INSERT INTO [SECURITY].[Modules]([Code],[Name])
	VALUES('opcua_browser','OPC UA Browser')

	SET @ModuleId = @@IDENTITY


	INSERT INTO [SECURITY].ModuleActions(ModuleId,Code,[Name],[Role])
	VALUES (@ModuleId,'read','Read','opcua_read')

	INSERT INTO [SECURITY].ModuleActions(ModuleId,Code,[Name],[Role])
	VALUES (@ModuleId,'write','Write','opcua_write')
