-- SETUP/RESTORE USERS IF OTHER DATABASES ARE PRESENT

USE [VIGIL-DVR]
GO

IF EXISTS (SELECT * FROM sys.databases WHERE name=N'VIGIL-POS')
BEGIN
	CREATE USER [vpos] FOR LOGIN [vpos]
	ALTER ROLE [db_datareader] ADD MEMBER [vpos]
	
	GRANT EXECUTE ON [dbo].[sp_insert_email] TO [vpos]
	GRANT EXECUTE ON [dbo].[sp_insert_email_notification] TO [vpos]
	GRANT EXECUTE ON [dbo].[sp_delete_vpos_email_notification] TO [vpos]
	GRANT EXECUTE ON [dbo].[sp_save_alarm_event] to [vpos]

	EXEC [VIGIL-POS]..sp_executesql N'IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N''vigil'') DROP USER [vigil]'
	EXEC [VIGIL-POS]..sp_executesql N'CREATE USER [vigil] FOR LOGIN [VIGIL]'
	EXEC [VIGIL-POS]..sp_executesql N'ALTER ROLE [db_owner] ADD MEMBER [vigil]'
END
GO

IF EXISTS (SELECT * FROM sys.databases WHERE name=N'VIGIL-Audit')
BEGIN
	CREATE USER [audit] FOR LOGIN [audit]
	ALTER ROLE [db_datareader] ADD MEMBER [audit]

	EXEC [VIGIL-Audit]..sp_executesql N'IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N''vigil'') DROP USER [vigil]'
	EXEC [VIGIL-Audit]..sp_executesql N'CREATE USER [vigil] FOR LOGIN [VIGIL]'
	EXEC [VIGIL-Audit]..sp_executesql N'ALTER ROLE [db_owner] ADD MEMBER [vigil]'
END
GO

IF EXISTS (SELECT * FROM sys.databases WHERE name=N'VIGIL-VA')
BEGIN
	CREATE USER [va] FOR LOGIN [va]
	ALTER ROLE [db_datareader] ADD MEMBER [va]

	EXEC [VIGIL-VA]..sp_executesql N'IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N''vigil'') DROP USER [vigil]'
	EXEC [VIGIL-VA]..sp_executesql N'CREATE USER [vigil] FOR LOGIN [VIGIL]'
	EXEC [VIGIL-VA]..sp_executesql N'ALTER ROLE [db_owner] ADD MEMBER [vigil]'
END
GO

IF EXISTS (SELECT * FROM sys.databases WHERE name=N'VIGIL-Settings')
BEGIN
	CREATE USER [settings] FOR LOGIN [settings]
	ALTER ROLE [db_datareader] ADD MEMBER [settings]

	EXEC [VIGIL-Settings]..sp_executesql N'IF EXISTS (SELECT * FROM sys.database_principals WHERE name = N''vigil'') DROP USER [vigil]'
	EXEC [VIGIL-Settings]..sp_executesql N'CREATE USER [vigil] FOR LOGIN [VIGIL]'
	EXEC [VIGIL-Settings]..sp_executesql N'ALTER ROLE [db_owner] ADD MEMBER [vigil]'
END
GO


-- MISC. FINAL ACTIONS

USE [master]
GO

ALTER DATABASE [VIGIL-DVR] SET  READ_WRITE 
GO
