/*
generate xml fragment for RDCMANAGER groups
run this scrript on hcimon
*/

USE [ControlCenter]


DECLARE @tpl VARCHAR(max)='      <server>
        <properties>
          <displayName>@ou@ - @name@</displayName>
          <name>@dns@</name>
        </properties>
      </server>
';


SELECT 
    e.[EN_designation]
    , s.[SE_designation]
    , s.[SE_DNS]
    --,s.*
    , REPLACE(REPLACE(REPLACE(@tpl, '@name@',[s].[SE_designation] ), '@dns@',[s].[SE_DNS]),'@ou@', [s].[SE_OU_code] ) AS fragment
FROM [dbo].[Server] s
    JOIN [dbo].[Entity] e ON e.[EN_id] = s.[SE_entity]
WHERE [e].[EN_designation] IN (
    --'Amavita'
    --'Coop-Vitality'
    'Sun Store'
)
ORDER BY [e].[EN_designation], [s].[SE_designation]


DECLARE @tplGrpProp AS NVARCHAR(MAX)='
      <properties>
        <expanded>False</expanded>
        <name>@grpName@</name>
      </properties>      
';
DECLARE @tplSrv AS NVARCHAR(MAX)='
<server>          
  <properties>
    <displayName>@srvName@</displayName>
    <name>@dns@</name>
  </properties>
  @srvs@
</server>  
';
DECLARE @xmlTpl AS NVARCHAR(MAX)='
<?xml version="1.0" encoding="utf-8"?>
<RDCMan programVersion="2.93" schemaVersion="3">
  <file>
    <credentialsProfiles />
    <properties>
      <expanded>False</expanded>
      <name>emtpy</name>
    </properties>
    @grps@
  </file>
  <connected />
  <favorites />
  <recentlyUsed />
</RDCMan>
'

;WITH cteGrp AS (
  SELECT e.EN_designation, e.EN_id
  FROM [dbo].[Entity] e
)
,cteSrv AS (
  SELECT 
    s.SE_designation AS srvName
    , s.SE_DNS AS dns
    , g.EN_designation AS grpName
    , ROW_NUMBER()OVER(PARTITION BY g.EN_designation ORDER BY g.EN_designation, s.SE_designation) AS rid
  FROM cteGrp g
    JOIN dbo.Server s ON s.SE_entity = g.EN_id
)
SELECT *
FROM cteSrv s
ORDER BY s.grpName ASC, s.srvName ASC 
;