/*
This script setups the needed permissions to enable Triapharm devops pipeline access to 
Triapharm databases

The permissions assigned are:
  Server level:
    * ALTER ANY DATABASE
    * ##MS_DatabaseManager##
    * ##MS_ServerPerformanceStateReader##
    * ##MS_ServerStateReader##
*/

USE master
GO

-- Check if the login exists, if not, create it
IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE name = N'sqlLogin-db-pipeline')
BEGIN
    CREATE LOGIN [sqlLogin-db-pipeline] WITH PASSWORD = N'tzJcO,O8S~k~u^zR6!JL';
END
ELSE
BEGIN
    ALTER LOGIN [sqlLogin-db-pipeline] WITH PASSWORD = N'tzJcO,O8S~k~u^zR6!JL';
END
GO

-- Grant access to DMVs
GRANT VIEW SERVER STATE TO [sqlLogin-db-pipeline];

GO

DECLARE @q NVARCHAR(MAX) = '
USE ? 
IF EXISTS(
  SELECT * 
  FROM sys.databases d
  WHERE d.name = DB_NAME()
  AND (
    [d].[source_database_id] IS NULL
    AND [d].[is_read_only] = 0
    AND [d].[is_in_standby] = 0
    AND [d].[state] = 0 --online
  )
)

BEGIN
  IF DB_NAME() NOT IN (''master'',''tempdb'',''model'')
  BEGIN
    IF NOT EXISTS (SELECT * FROM ?.sys.database_principals WHERE name = N''sqlLogin-db-pipeline'')
    BEGIN
        CREATE USER [sqlLogin-db-pipeline] FOR LOGIN [sqlLogin-db-pipeline];
    END
  END

  IF DB_NAME() = ''msdb''
  BEGIN
    --allow jobs creation / modification / deletion
    ALTER ROLE [SQLAgentOperatorRole] ADD MEMBER [sqlLogin-db-pipeline];

  END

  IF DB_NAME() NOT IN (''master'',''msdb'',''tempdb'',''model'')
  BEGIN
    --give permission to alter / create / drop objects in db
    ALTER ROLE [db_ddladmin] ADD MEMBER [sqlLogin-db-pipeline];
  
    -- Grant permissions for change tracking and broker management
    GRANT ALTER ON DATABASE::[?] TO [sqlLogin-db-pipeline];


  END
END
'
EXEC sys.sp_MSforeachdb @command1 = @q





