USE [master]

/* Create SQL Master key */
IF NOT EXISTS(SELECT 1 FROM sys.symmetric_keys WHERE name like '%DatabaseMasterKey%')
BEGIN
  EXEC('CREATE MASTER KEY ENCRYPTION BY PASSWORD = ''$mk''')

  /* Backup SQL Master key */
  EXEC('BACKUP MASTER KEY TO FILE = ''$bck'' ENCRYPTION BY PASSWORD = ''$mk''')
END

/* Create Atlas Service Broker Certificate */
IF NOT EXISTS(SELECT 1 FROM sys.certificates WHERE name = 'TriaPharmSQLCert')
BEGIN
  EXEC('CREATE CERTIFICATE TriaPharmSQLCert FROM FILE = ''D:\SQLDatabaseDump\Certificates\TriaPharmSQLCert.cer'' WITH PRIVATE KEY (FILE = ''D:\SQLDatabaseDump\Certificates\TriaPharmSQLCert.pvk'', DECRYPTION BY PASSWORD = ''$cert'');')
END

/* SQL Broker Endpoint Creation */
IF NOT EXISTS ( SELECT 1 FROM sys.tcp_endpoints WHERE name = 'ServiceBrokerEndpoint4022')
BEGIN
  CREATE ENDPOINT [ServiceBrokerEndpoint4022]
      STATE=STARTED
      AS TCP (LISTENER_PORT = 4022, LISTENER_IP = ALL)
      FOR SERVICE_BROKER (MESSAGE_FORWARDING = DISABLED
, MESSAGE_FORWARD_SIZE = 10
, AUTHENTICATION = CERTIFICATE TriaPharmSQLCert
, ENCRYPTION = REQUIRED ALGORITHM AES)

EXEC('GRANT CONNECT on ENDPOINT::[ServiceBrokerEndpoint4022] TO [PUBLIC]')

END

USE [Arizona]

/*------------------- Declaration des variables --------------------*/
DECLARE @cvCurrentOrganizationalUnit              int,
        @subsidiary_id                            int,
        @skip                                     tinyint,
        @servicenamecheck                         varchar(255),
        @out_default_value                        varchar(60),
        @format                                   varchar(60),
        @ou                                       varchar(3),
        @envtype                                  char(1),
        @envtype2                                 char(1),
        @ServiceName                              varchar(150),
        @RteAddress                               varchar(150),
        @stmt                                     nvarchar(4000)
  
  

/*------------ Affectation des parametres aux variables ------------*/

SET @cvCurrentOrganizationalUnit = null
SET @subsidiary_id = null
SET @ou = ''
SET @skip = 0

SELECT @envtype = CASE WHEN [Type] = 'DEVE' OR [Type] = 'VALI' THEN 'D' ELSE 'P' END FROM master.cfg.InstanceContext
SELECT @envtype2 = CASE WHEN [Type] = 'DEVE' THEN 'D' WHEN [Type] = 'VALI' THEN 'T' ELSE 'P' END FROM master.cfg.InstanceContext




/* ------------------------------------------------------------------------------------------------------------------------------------- */
/* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ 1 : RETRIEVE FORMAT AND OU CODE /////////////////////////////////////////////////// */
/* ------------------------------------------------------------------------------------------------------------------------------------- */
    
IF EXISTS(SELECT 1 FROM [master].[cfg].[InstanceContext] WHERE Business = 'TPPHAR')
BEGIN
  /* Get the cvCurrentOrganizationalUnit */
  EXEC arizona.dbo.sp_bmc_Bmc_Applic_Default 
       @in_job_type        = 3,
       @in_param_int_1     = null,
       @in_param_int_2     = null,
       @in_param_varchar_1 = 'cvCurrentOrganizationalUnit',
       @out_default_value  = @out_default_value OUTPUT,
       @out_param_int_1    = null;
  
  SELECT @cvCurrentOrganizationalUnit = convert(int,@out_default_value);

  /* Get the subsidiary id and OU code */
  SELECT @subsidiary_id = ou.OU_subsidiary, @ou = ou.OU_Code
    FROM arizona.dbo.Organizational_unit ou  with (nolock)
    WHERE ou.Organizational_unit_ID = @cvCurrentOrganizationalUnit;

  /* Get the current format */
  SELECT @format = UPPER(sub.SUB_code)
    FROM arizona.dbo.Subsidiary sub  with (nolock)
    WHERE sub.Subsidiary_ID = @subsidiary_id;
  
  /* Check if we have a value, if not leave this SP */
  IF @format is null
  BEGIN
    PRINT 'ERROR: Format is not found!'
    SET @skip = 1
  END

  IF @ou = ''
  BEGIN
    PRINT 'ERROR: OU is not found!'
    SET @skip = 1
  END

  /* Change the value into a compatible format */
  IF @format = 'COOP'
  BEGIN
    SET @format = 'CVI'
  END

  IF @format = 'CENT'
  BEGIN
    SET @format = 'SUN'
  END

  IF @format = '000'
  BEGIN
    SET @format = 'AAI'
  END
	


/* ------------------------------------------------------------------------------------------------------------------------------------- */
/* \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ 2 : CREATE SERVICE BROEKR OBJECTS ////////////////////////////////////////////////// */
/* ------------------------------------------------------------------------------------------------------------------------------------- */

  IF @skip = 0
  BEGIN

    /* Activate Service Broker */
    IF NOT EXISTS (SELECT 1 FROM sys.databases WHERE name = 'Arizona' and is_broker_enabled = 1)
    BEGIN
      IF (SERVERPROPERTY('EngineEdition') <> 8)
       BEGIN
         ALTER DATABASE [Arizona] SET ENABLE_BROKER
       END
    END

    /* Create Atlas Route */
    IF NOT EXISTS (select 1 from sys.routes where name = '//ATLAS/' + @envtype + 'GALATLAS/Atlas')
    BEGIN

      SET @ServiceName = '//ATLAS/' + @envtype + 'GALATLAS/AtlasDataCheckRequestService'
      IF @envtype = 'P'
      BEGIN
      SET @RteAddress = 'TCP://atlas.centralinfra.net:4022'
      END
      ELSE
      BEGIN
      SET @RteAddress = 'TCP://atlas-dev.centralinfra.net:4022'
      END

      SET @stmt = N'CREATE ROUTE [//ATLAS/' + @envtype + 'GALATLAS/Atlas] WITH SERVICE_NAME = ''' + @ServiceName + ''', ADDRESS=''' + @RteAddress + ''' ;'
	    EXEC(@stmt)

    END

	/* Create Ceres Route */
    IF NOT EXISTS (select 1 from sys.routes where name = '//GAIA/' + @envtype2 + 'GALCTP/Ceres')
    BEGIN

      SET @ServiceName = '//GAIA/' + @envtype2 + 'GALCTP/CeresRequestService'
      IF @envtype = 'P'
      BEGIN
        SET @RteAddress = 'TCP://SWGCMDB01.centralinfra.net:4022'
      END
	  IF @envtype2 = 'T'
      BEGIN
        SET @RteAddress = 'TCP://triafin-test.centralinfra.net:4022'
      END
	  IF @envtype2 = 'D'
      BEGIN
        SET @RteAddress = 'TCP://triafin-integration.centralinfra.net:4022'
      END
	        
      SET @stmt = N'CREATE ROUTE [//GAIA/' + @envtype2 + 'GALCTP/Ceres] WITH SERVICE_NAME = ''' + @ServiceName + ''', ADDRESS=''' + @RteAddress + ''' ;'
	    EXEC(@stmt)

    END

    /* Drop service ATLAS */
    SELECT @servicenamecheck = name FROM sys.services WHERE name like '%AtlasDataCheckProcessingService%'

    IF EXISTS (SELECT 1 from sys.services WHERE name = @servicenamecheck)
    BEGIN
      EXEC('DROP SERVICE [' + @servicenamecheck +']')
    END
		
    /* Drop contract ATLAS */
    IF EXISTS (SELECT 1 from sys.service_contracts WHERE name = 'AtlasDataCheckContract')
    BEGIN
      DROP CONTRACT AtlasDataCheckContract
    END

    /*  DROP AND CREATE MESSAGES ATLAS */
    IF EXISTS (SELECT 1 from sys.service_message_types WHERE name = 'AtlasDataCheckSenderMessageType')
    BEGIN
      DROP MESSAGE TYPE [AtlasDataCheckSenderMessageType]
    END

    IF NOT EXISTS (SELECT 1 from sys.service_message_types WHERE name = 'AtlasDataCheckSenderMessageType')
    BEGIN
      CREATE MESSAGE TYPE AtlasDataCheckSenderMessageType validation=well_formed_xml
    END

    IF EXISTS (SELECT 1 from sys.service_message_types WHERE name = 'AtlasDataCheckReceiverMessageType')
    BEGIN
      DROP MESSAGE TYPE [AtlasDataCheckReceiverMessageType]
    END

    IF NOT EXISTS (SELECT 1 from sys.service_message_types WHERE name = 'AtlasDataCheckReceiverMessageType')
    BEGIN
      CREATE MESSAGE TYPE AtlasDataCheckReceiverMessageType validation=well_formed_xml
    END

    /* CREATE CONTRACT ATLAS */
    IF NOT EXISTS (SELECT 1 FROM sys.service_contracts WHERE name = 'AtlasDataCheckContract')
    BEGIN
      CREATE CONTRACT AtlasDataCheckContract
      (
        AtlasDataCheckSenderMessageType SENT BY INITIATOR,
        AtlasDataCheckReceiverMessageType SENT BY TARGET
      )
    END

    /* DROP AND CREATE QUEUE ATLAS */
    IF EXISTS (SELECT 1 from sys.service_queues WHERE name = 'AtlasDataCheckProcessingQueue')
    BEGIN
      DROP QUEUE AtlasDataCheckProcessingQueue
    END

    IF NOT EXISTS (SELECT 1 from sys.service_queues WHERE name = 'AtlasDataCheckProcessingQueue')
    BEGIN
      CREATE QUEUE AtlasDataCheckProcessingQueue
        WITH STATUS = ON ,
        ACTIVATION (  
                    STATUS = ON  ,   
                    PROCEDURE_NAME = [atl].[ProcessCheckData] ,  
                    MAX_QUEUE_READERS = 10 ,   
                    EXECUTE AS SELF   
                    )
    END

    /* CREATE SERVICE ATLAS */
    SET @servicenamecheck = '//' +  @format+@ou + 'APS/APSSQL/AtlasDataCheckProcessingService'

    IF NOT EXISTS (SELECT 1 FROM sys.service_contracts WHERE name = @servicenamecheck)
    BEGIN
      EXEC('CREATE SERVICE [' +  @servicenamecheck + '] ON QUEUE AtlasDataCheckProcessingQueue (AtlasDataCheckContract)')
    END
  
    /* SET SECURITY ATLAS */
    EXEC('GRANT SEND on service::[' +  @servicenamecheck + '] TO PUBLIC')




	/* Drop service CERES */
    SELECT @servicenamecheck = name FROM sys.services WHERE name like '%CeresProcessingService%'

    IF EXISTS (SELECT 1 from sys.services WHERE name = @servicenamecheck)
    BEGIN
      EXEC('DROP SERVICE [' + @servicenamecheck +']')
    END
		
    /* Drop contract CERES */
    IF EXISTS (SELECT 1 from sys.service_contracts WHERE name = 'CeresContract')
    BEGIN
      DROP CONTRACT CeresContract
    END

    /*  DROP AND CREATE MESSAGES CERES */
    IF EXISTS (SELECT 1 from sys.service_message_types WHERE name = 'CeresSenderMessageType')
    BEGIN
      DROP MESSAGE TYPE [CeresSenderMessageType]
    END

    IF NOT EXISTS (SELECT 1 from sys.service_message_types WHERE name = 'CeresSenderMessageType')
    BEGIN
      CREATE MESSAGE TYPE CeresSenderMessageType validation=well_formed_xml
    END

    IF EXISTS (SELECT 1 from sys.service_message_types WHERE name = 'CeresReceiverMessageType')
    BEGIN
      DROP MESSAGE TYPE [CeresReceiverMessageType]
    END

    IF NOT EXISTS (SELECT 1 from sys.service_message_types WHERE name = 'CeresReceiverMessageType')
    BEGIN
      CREATE MESSAGE TYPE CeresReceiverMessageType validation=well_formed_xml
    END

    /* CREATE CONTRACT CERES */
    IF NOT EXISTS (SELECT 1 FROM sys.service_contracts WHERE name = 'CeresContract')
    BEGIN
      CREATE CONTRACT CeresContract
      (
        CeresSenderMessageType SENT BY INITIATOR,
        CeresReceiverMessageType SENT BY TARGET
      )
    END

    /* DROP AND CREATE QUEUE CERES */
    IF EXISTS (SELECT 1 from sys.service_queues WHERE name = 'CeresProcessingQueue')
    BEGIN
      DROP QUEUE CeresProcessingQueue
    END

    IF NOT EXISTS (SELECT 1 from sys.service_queues WHERE name = 'CeresProcessingQueue')
    BEGIN
      CREATE QUEUE CeresProcessingQueue
        WITH STATUS = ON ,
        ACTIVATION (  
                    STATUS = ON  ,   
                    PROCEDURE_NAME = [crs].[ProcessRequest] ,  
                    MAX_QUEUE_READERS = 10 ,   
                    EXECUTE AS SELF   
                    )
    END

    /* CREATE SERVICE CERES */
    SET @servicenamecheck = '//' +  @format+@ou + 'APS/APSSQL/CeresProcessingService'

    IF NOT EXISTS (SELECT 1 FROM sys.service_contracts WHERE name = @servicenamecheck)
    BEGIN
      EXEC('CREATE SERVICE [' +  @servicenamecheck + '] ON QUEUE CeresProcessingQueue (CeresContract)')
    END
  
    /* SET SECURITY ATLAS */
    EXEC('GRANT SEND on service::[' +  @servicenamecheck + '] TO PUBLIC')
    
  END
END
