-- This lives on the main instance
--

USE MASTER
GO

CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'StrongPW1'
GO

-- 
-- Step 1-Certs: Create a certificate for dialog encryption
-- This will be used to represent your service user in the other databasse
--

CREATE CERTIFICATE endpoint_cert1
with subject = 'endpoint_cert1',
start_date = '09/01/2005';
go

--
-- Back the certificate up to a file
-- This only backs up the public key, not the private key
--
BACKUP CERTIFICATE endpoint_cert1
TO FILE = 'c:\certs\endpoint_cert1.cer'
GO

--you need to create an endpoint in order to enable communication
--outside of this instance
CREATE ENDPOINT endpoint1
STATE = STARTED
AS TCP
(
  LISTENER_PORT = 4567
)
FOR SERVICE_BROKER
(
  AUTHENTICATION = CERTIFICATE endpoint_cert1,
  ENCRYPTION = REQUIRED
);
go

--check that the endpoint has been created
select * from sys.endpoints;
go

--
-- Step 3-Certs:
-- Create a user in this database (without login or any other priv)
--

--create a login and a user which you eventually will assign a public
--key from the cert in the remote master db to
create login endpoint_connect1
with password = 'StrongPW1';
go

create user endpoint_connect_user1
from login endpoint_connect1;
go

--grant connect to the endpoint to the login
grant connect on endpoint::endpoint1 to endpoint_connect1
go

--
-- The user owns a certificate created by using
-- the public key only-portion from the partner's database
--

create certificate remote_endpoint_cert1
authorization endpoint_connect_user1
from file = 'c:\certs\endpoint_cert2.cer';
go

USE BrokerDB1
GO

select * from sys.routes

--create a route to the remote service, we know it'll be called rem_s2
create route [InvService_Route]
with
service_name = 'InvService',
address = 'TCP://localhost:4321';
go