-- This lives on the remote instance
--

USE MASTER
GO

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

CREATE MASTER KEY ENCRYPTION BY PASSWORD = 'StrongPW1'
GO


CREATE CERTIFICATE endpoint_cert2
with subject = 'endpoint_cert2',
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_cert2
TO FILE = 'c:\certs\endpoint_cert2.cer'
GO


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

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

--
-- Step 4-Endpoints:
-- 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_connect2
with password = 'StrongPW1';
go

create user endpoint_connect_user2
from login endpoint_connect2;
go

--grant connect to the endpoint to the login
grant connect on endpoint::endpoint2 to endpoint_connect2
go

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

create certificate remote_endpoint_cert2
authorization endpoint_connect_user2
from file = 'c:\certs\endpoint_cert1.cer';
go

USE BrokerDB2
GO

--create a route to the remote service
create route [InvInitiator_Route]
with
service_name = 'InvInitiator',
address = 'TCP://localhost:4567';
go

select * from sys.routes