{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "sshPublicKey": {
      "type": "string",
      "metadata": {
        "description": "The SSH public key to access the Virtual Machine."
      }
    },
    "allowedSourceAddressPrefix": {
      "type": "string",
      "defaultValue": "0.0.0.0/0",
      "metadata": {
        "description": "CIDR range or IP address allowed to access the Yellowbrick Deployer. Examples: '192.168.1.0/24' for a subnet, '203.0.113.45/32' for a single IP, or '0.0.0.0/0' for any source."
      }
    }
  },
  "variables": {
    "location": "[resourceGroup().location]",
    "vmName": "[concat('yb-deployer-', uniqueString(resourceGroup().id))]",
    "vmSize": "Standard_DC2s_v2",
    "virtualNetworkName": "[concat(variables('vmName'), '-vnet')]",
    "virtualNetworkAddressPrefixes": [
      "10.10.0.0/16"
    ],
    "subnetName": "default",
    "virtualNetworkSubnets": [
      {
        "name": "default",
        "properties": {
          "addressPrefix": "10.10.0.0/24"
        }
      }
    ],
    "publicIpAddressSku": "Standard",
    "publicIpAddressType": "Static",
    "networkSecurityGroupName": "[concat(variables('vmName'), '-nsg')]",
    "publicIpAddressName": "[concat(variables('vmName'), '-ip')]",
    "networkInterfaceName": "[concat(variables('vmName'), '-nic')]",
    "subnetRef": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('virtualNetworkName'), variables('subnetName'))]",
    "nsgId": "[resourceId('Microsoft.Network/networkSecurityGroups', variables('networkSecurityGroupName'))]",
    "roleId": "[guid(subscription().subscriptionId, resourceGroup().Name, variables('vmName'))]",
    "roleName": "[concat('Yellowbrick Enterprise Edition installer role for ', variables('vmName'))]",
    "roleDescription": "The role required to run the Yellowbrick Enterprise Edition Installer",
    "accesskey": "[concat(uniqueString(subscription().subscriptionId, resourceGroup().id), uniqueString(subscription().subscriptionId, resourceGroup().id, variables('vmName')))]",
    "networkSecurityGroupRules": [
      {
        "name": "SSH",
        "properties": {
          "priority": 300,
          "protocol": "TCP",
          "access": "Allow",
          "direction": "Inbound",
          "sourceAddressPrefix": "[parameters('allowedSourceAddressPrefix')]",
          "sourcePortRange": "*",
          "destinationAddressPrefix": "*",
          "destinationPortRange": "22"
        }
      },
      {
        "name": "HTTPS",
        "properties": {
          "priority": 310,
          "protocol": "TCP",
          "access": "Allow",
          "direction": "Inbound",
          "sourceAddressPrefix": "[parameters('allowedSourceAddressPrefix')]",
          "sourcePortRange": "*",
          "destinationAddressPrefix": "*",
          "destinationPortRange": "443"
        }
      }
    ],
    "pipDeleteOption": "Detach",
    "enableAcceleratedNetworking": true,
    "virtualMachineZone": "1",
    "osDiskType": "Premium_LRS",
    "osDiskDeleteOption": "Delete",
    "nicDeleteOption": "Detach",
    "adminUsername": "azureuser",
    "tags": {
      "ybd": "deployer"
    },
    "imageReference": {
      "communityGalleryImageId": "/CommunityGalleries/yellowbrick-859da308-93f1-40a0-8185-0ec7fc91ad5e/Images/yb-enterprise-edition/Versions/7.4.2"
    },
    "installerPermissions": [
      {
        "actions": [
          "Microsoft.Resources/subscriptions/resourcegroups/read",
          "Microsoft.Network/virtualNetworks/read",
          "Microsoft.Network/virtualNetworks/write",
          "Microsoft.Network/virtualNetworks/delete",
          "Microsoft.Network/virtualNetworks/subnets/read",
          "Microsoft.Network/virtualNetworks/subnets/join/action",
          "Microsoft.ContainerRegistry/registries/read",
          "Microsoft.ContainerRegistry/registries/write",
          "Microsoft.ContainerRegistry/registries/delete",
          "Microsoft.ContainerRegistry/registries/generateCredentials/action",
          "Microsoft.ContainerRegistry/registries/pull/read",
          "Microsoft.ContainerRegistry/registries/push/write",
          "Microsoft.ManagedIdentity/userAssignedIdentities/write",
          "Microsoft.ManagedIdentity/userAssignedIdentities/read",
          "Microsoft.ManagedIdentity/userAssignedIdentities/delete",
          "Microsoft.ContainerService/managedClusters/read",
          "Microsoft.ContainerService/managedClusters/write",
          "Microsoft.ContainerService/managedClusters/delete",
          "Microsoft.ContainerService/managedClusters/listClusterAdminCredential/action",
          "Microsoft.ContainerService/managedClusters/agentPools/read",
          "Microsoft.ContainerService/managedClusters/agentPools/write",
          "Microsoft.ContainerService/managedClusters/agentPools/delete",
          "Microsoft.Authorization/roleAssignments/read",
          "Microsoft.Authorization/roleAssignments/write",
          "Microsoft.Authorization/roleAssignments/delete",
          "Microsoft.Authorization/roleDefinitions/read",
          "Microsoft.Authorization/roleDefinitions/write",
          "Microsoft.Authorization/roleDefinitions/delete",
          "Microsoft.ManagedIdentity/userAssignedIdentities/federatedIdentityCredentials/read",
          "Microsoft.ManagedIdentity/userAssignedIdentities/federatedIdentityCredentials/write",
          "Microsoft.ManagedIdentity/userAssignedIdentities/federatedIdentityCredentials/delete",
          "Microsoft.Storage/storageAccounts/read",
          "Microsoft.Storage/storageAccounts/write",
          "Microsoft.Storage/storageAccounts/delete",
          "Microsoft.Storage/storageAccounts/blobServices/containers/read",
          "Microsoft.Storage/storageAccounts/blobServices/containers/write",
          "Microsoft.OperationalInsights/workspaces/sharedkeys/read"
        ]
      }
    ]
  },
  "resources": [
    {
      "type": "Microsoft.Network/virtualNetworks",
      "apiVersion": "2023-04-01",
      "name": "[variables('virtualNetworkName')]",
      "location": "[variables('location')]",
      "tags": "[variables('tags')]",
      "properties": {
        "addressSpace": {
          "addressPrefixes": "[variables('virtualNetworkAddressPrefixes')]"
        },
        "subnets": "[variables('virtualNetworkSubnets')]"
      }
    },
    {
      "type": "Microsoft.Network/networkSecurityGroups",
      "apiVersion": "2023-06-01",
      "name": "[variables('networkSecurityGroupName')]",
      "location": "[variables('location')]",
      "tags": "[variables('tags')]",
      "properties": {
        "securityRules": "[variables('networkSecurityGroupRules')]"
      }
    },
    {
      "type": "Microsoft.Network/publicIpAddresses",
      "apiVersion": "2023-06-01",
      "name": "[variables('publicIpAddressName')]",
      "location": "[variables('location')]",
      "tags": "[variables('tags')]",
      "sku": {
        "name": "[variables('publicIpAddressSku')]"
      },
      "properties": {
        "publicIpAllocationMethod": "[variables('publicIpAddressType')]"
      }
    },
    {
      "type": "Microsoft.Network/networkInterfaces",
      "apiVersion": "2023-06-01",
      "name": "[variables('networkInterfaceName')]",
      "location": "[variables('location')]",
      "tags": "[variables('tags')]",
      "dependsOn": [
        "[resourceId('Microsoft.Network/virtualNetworks/', variables('virtualNetworkName'))]",
        "[resourceId('Microsoft.Network/networkSecurityGroups/', variables('networkSecurityGroupName'))]",
        "[resourceId('Microsoft.Network/publicIpAddresses/', variables('publicIpAddressName'))]"
      ],
      "properties": {
        "ipConfigurations": [
          {
            "name": "ipconfig1",
            "properties": {
              "subnet": {
                "id": "[variables('subnetRef')]"
              },
              "privateIPAllocationMethod": "Dynamic",
              "publicIpAddress": {
                "id": "[resourceId('Microsoft.Network/publicIpAddresses', variables('publicIpAddressName'))]",
                "properties": {
                  "deleteOption": "[variables('pipDeleteOption')]"
                }
              }
            }
          }
        ],
        "enableAcceleratedNetworking": "[variables('enableAcceleratedNetworking')]",
        "networkSecurityGroup": {
          "id": "[variables('nsgId')]"
        }
      }
    },
    {
      "type": "Microsoft.Compute/virtualMachines",
      "apiVersion": "2023-09-01",
      "name": "[variables('vmName')]",
      "location": "[variables('location')]",
      "tags": "[variables('tags')]",
      "dependsOn": [
        "[resourceId('Microsoft.Network/networkInterfaces/', variables('networkInterfaceName'))]"
      ],
      "zones": [
        "[variables('virtualMachineZone')]"
      ],
      "identity": {
        "type": "systemAssigned"
      },
      "properties": {
        "hardwareProfile": {
          "vmSize": "[variables('vmSize')]"
        },
        "storageProfile": {
          "osDisk": {
            "createOption": "fromImage",
            "managedDisk": {
              "storageAccountType": "[variables('osDiskType')]"
            },
            "deleteOption": "[variables('osDiskDeleteOption')]"
          },
          "imageReference": "[variables('imageReference')]"
        },
        "networkProfile": {
          "networkInterfaces": [
            {
              "id": "[resourceId('Microsoft.Network/networkInterfaces', variables('networkInterfaceName'))]",
              "properties": {
                "deleteOption": "[variables('nicDeleteOption')]"
              }
            }
          ]
        },
        "additionalCapabilities": {
          "hibernationEnabled": false
        },
        "osProfile": {
          "computerName": "[variables('vmName')]",
          "adminUsername": "[variables('adminUsername')]",
          "customData": "[base64(concat(base64ToString('I2Nsb3VkLWNvbmZpZwp3cml0ZV9maWxlczoKICAtIHBhdGg6IC9vcHQveWJkL2Jvb3RzdHJhcC5zaAogICAgcGVybWlzc2lvbnM6IDA3NTUKICAgIGNvbnRlbnQ6IHwKICAgICAgIyEvYmluL2Jhc2gKICAgICAgc2V0IC1lCiAgICAgIGZ1bmN0aW9uIGxvZygpIHsKICAgICAgICAgIGVjaG8gJChkYXRlIC0tcmZjLTMzMzk9c2Vjb25kcykgJDEgPj4gL3Zhci9sb2cvYm9vdHN0cmFwLmxvZwogICAgICB9CiAgICAgIGxvZyAiQm9vdHN0cmFwIHNjcmlwdCBzdGFydGVkIgogICAgICBzZWQgLWkgInNfXkV4ZWNTdGFydD0vb3B0L3liZC95Yi1pbnN0YWxsIGludGVyYWN0aXZlIC0tcG9ydCA0NDNcJF9FeGVjU3RhcnQ9L29wdC95YmQveWItaW5zdGFsbCBpbnRlcmFjdGl2ZSAtLXBvcnQgNDQzIA=='),'--key ',variables('accesskey'),' --allow ',reference(resourceId('Microsoft.Network/publicIpAddresses', variables('publicIpAddressName'))).ipAddress,base64ToString('LzMyXyIgL2V0Yy9zeXN0ZW1kL3N5c3RlbS95Yi1pbnN0YWxsLnNlcnZpY2UKICAgICAgc3lzdGVtY3RsIGRhZW1vbi1yZWxvYWQKICAgICAgc3lzdGVtY3RsIHJlc3RhcnQgeWItaW5zdGFsbC5zZXJ2aWNlCiAgICAgIGlmIFsgJD8gLWVxIDAgXTsgdGhlbgogICAgICAgICAgbG9nICJTZXJ2aWNlIHJlc3RhcnRlZCIKICAgICAgZWxzZQogICAgICAgICAgbG9nICJTZXJ2aWNlIGZhaWxlZCB0byByZXN0YXJ0IgogICAgICBmaQogICAgICBsb2cgIkJvb3RzdHJhcCBzY3JpcHQgY29tcGxldGUiCnJ1bmNtZDoKICAtIGJhc2ggL29wdC95YmQvYm9vdHN0cmFwLnNoCg==')))]",
          "linuxConfiguration": {
            "disablePasswordAuthentication": true,
            "ssh": {
              "publicKeys": [
                {
                  "path": "[concat('/home/', variables('adminUsername'), '/.ssh/authorized_keys')]",
                  "keyData": "[parameters('sshPublicKey')]"
                }
              ]
            }
          }
        }
      }
    },
    {
      "type": "Microsoft.Authorization/roleDefinitions",
      "apiVersion": "2022-04-01",
      "name": "[variables('roleId')]",
      "properties": {
        "roleName": "[variables('roleName')]",
        "description": "[variables('roleDescription')]",
        "permissions": "[variables('installerPermissions')]",
        "assignableScopes": [
          "[resourceGroup().id]"
        ]
      }
    },
    {
      "type": "Microsoft.Authorization/roleAssignments",
      "apiVersion": "2022-04-01",
      "name": "[guid(subscription().subscriptionId, resourceGroup().Name, variables('roleName'))]",
      "dependsOn": [
        "[resourceId('Microsoft.Authorization/roleDefinitions', variables('roleId'))]",
        "[resourceId('Microsoft.Compute/virtualMachines', variables('vmName'))]"
      ],
      "properties": {
        "roleDefinitionId": "[resourceId('Microsoft.Authorization/roleDefinitions', variables('roleId'))]",
        "principalId": "[reference(resourceId('Microsoft.Compute/virtualMachines', variables('vmName')), '2023-09-01', 'Full').identity.principalId]",
        "principalType": "ServicePrincipal"
      }
    }
  ],
  "outputs": {
    "Deployer": {
      "type": "string",
      "value": "[concat('https://',reference(resourceId('Microsoft.Network/publicIpAddresses', variables('publicIpAddressName'))).ipAddress, '?deployerAccessKey=', variables('accesskey'), '&deployerPlatform=azure')]"
    },
    "Deployer Access Key": {
      "type": "string",
      "value": "[variables('accesskey')]"
    },
    "Deployer IP": {
      "type": "string",
      "value": "[reference(resourceId('Microsoft.Network/publicIpAddresses', variables('publicIpAddressName'))).ipAddress]"
    }
  }
}
