{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.46.1.21595",
      "templateHash": "1962762991268700069"
    }
  },
  "parameters": {
    "baseName": {
      "type": "string",
      "defaultValue": "dotmarc",
      "metadata": {
        "description": "Base name used to derive resource names (e.g. \"dotmarc\")."
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Azure region for all resources."
      }
    },
    "containerImage": {
      "type": "string",
      "defaultValue": "ghcr.io/homotechsual/dotmarc:latest",
      "metadata": {
        "description": "Container image to deploy, e.g. ghcr.io/homotechsual/dotmarc:latest"
      }
    },
    "postgresAdminUsername": {
      "type": "string",
      "defaultValue": "dotmarc",
      "metadata": {
        "description": "PostgreSQL administrator username."
      }
    },
    "postgresAdminPassword": {
      "type": "securestring",
      "metadata": {
        "description": "PostgreSQL administrator password."
      }
    },
    "graphClientId": {
      "type": "string",
      "metadata": {
        "description": "MAILBOX app registration (the one named dotmarc-mailbox, app-only Microsoft Graph): its Application (client) ID, a GUID such as 00000000-0000-0000-0000-000000000000. Find it on the app registration's Overview page in Microsoft Entra."
      }
    },
    "graphTenantId": {
      "type": "string",
      "metadata": {
        "description": "Your Microsoft Entra tenant (directory) ID, a GUID. Used by the MAILBOX app registration (dotmarc-mailbox). Find it on the app registration's Overview page."
      }
    },
    "graphMailboxAddress": {
      "type": "string",
      "metadata": {
        "description": "The shared mailbox that receives DMARC aggregate reports, e.g. dmarc@contoso.com. The MAILBOX app registration (dotmarc-mailbox) must be scoped to read it."
      }
    },
    "graphTlsrptMailboxAddress": {
      "type": "string",
      "defaultValue": "",
      "metadata": {
        "description": "Optional separate mailbox for receiving SMTP TLS Reporting aggregate reports. Leave blank to use the main mailbox."
      }
    },
    "entraIdTenantId": {
      "type": "string",
      "metadata": {
        "description": "Your Microsoft Entra tenant (directory) ID, a GUID. Used by the DASHBOARD app registration (dotmarc-dashboard) for sign-in. Usually the same value as graphTenantId."
      }
    },
    "entraIdClientId": {
      "type": "string",
      "metadata": {
        "description": "DASHBOARD app registration (the one named dotmarc-dashboard, delegated sign-in): its Application (client) ID, a GUID. This is a different app registration from the mailbox one."
      }
    },
    "initialAdminEmails": {
      "type": "string",
      "minLength": 1,
      "metadata": {
        "description": "REQUIRED. Comma-separated list of email addresses granted the Admin role the first time the app starts with no existing access grants, such as you@contoso.com. Not secret, just email addresses. Only takes effect on that first startup, but the form needs a value every time. Without one nobody can sign in."
      }
    },
    "enableMtaStsHosting": {
      "type": "bool",
      "defaultValue": false,
      "metadata": {
        "description": "Enable MTA-STS policy hosting (see getting-started.mdx). Grants the container app a narrowly-scoped custom RBAC role to manage its own custom domains and managed certificates — off by default, since it widens the managed identity beyond Key Vault Secrets User."
      }
    },
    "mtaStsHostingHostname": {
      "type": "string",
      "defaultValue": "",
      "metadata": {
        "description": "Hostname customers CNAME mta-sts.<their-domain> to. Only meaningful when enableMtaStsHosting is true. The Container App's own generated hostname isn't known until after a first deployment (see containerAppUrl output) — leave this blank on that first deployment, then set it on a follow-up update, same two-step pattern as the OIDC redirect URI below."
      }
    },
    "enableKeyVaultWrite": {
      "type": "bool",
      "defaultValue": false,
      "metadata": {
        "description": "Grant the container app write access to its own Key Vault, used to store runtime-editable secrets (HaloPSA API client secret, Cloudflare/Azure DNS push OAuth client secrets) entered through their respective settings pages rather than in Postgres. Off by default, since it widens the managed identity beyond Key Vault Secrets User (read-only) — see deploy-to-azure.mdx."
      }
    }
  },
  "variables": {
    "postgresServerName": "[format('{0}-pg-{1}', parameters('baseName'), uniqueString(resourceGroup().id))]",
    "keyVaultName": "[format('{0}-kv-{1}', take(parameters('baseName'), 7), uniqueString(resourceGroup().id))]",
    "logAnalyticsName": "[format('{0}-logs', parameters('baseName'))]",
    "containerAppEnvName": "[format('{0}-env', parameters('baseName'))]",
    "containerAppName": "[parameters('baseName')]",
    "postgresDatabaseName": "dotmarc"
  },
  "resources": [
    {
      "type": "Microsoft.DBforPostgreSQL/flexibleServers",
      "apiVersion": "2024-08-01",
      "name": "[variables('postgresServerName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard_B1ms",
        "tier": "Burstable"
      },
      "properties": {
        "version": "18",
        "administratorLogin": "[parameters('postgresAdminUsername')]",
        "administratorLoginPassword": "[parameters('postgresAdminPassword')]",
        "storage": {
          "storageSizeGB": 32
        },
        "network": {
          "publicNetworkAccess": "Enabled"
        }
      }
    },
    {
      "type": "Microsoft.DBforPostgreSQL/flexibleServers/databases",
      "apiVersion": "2024-08-01",
      "name": "[format('{0}/{1}', variables('postgresServerName'), variables('postgresDatabaseName'))]",
      "dependsOn": [
        "[resourceId('Microsoft.DBforPostgreSQL/flexibleServers', variables('postgresServerName'))]"
      ]
    },
    {
      "type": "Microsoft.DBforPostgreSQL/flexibleServers/firewallRules",
      "apiVersion": "2024-08-01",
      "name": "[format('{0}/{1}', variables('postgresServerName'), 'AllowAzureServices')]",
      "properties": {
        "startIpAddress": "0.0.0.0",
        "endIpAddress": "0.0.0.0"
      },
      "dependsOn": [
        "[resourceId('Microsoft.DBforPostgreSQL/flexibleServers', variables('postgresServerName'))]"
      ]
    },
    {
      "type": "Microsoft.OperationalInsights/workspaces",
      "apiVersion": "2023-09-01",
      "name": "[variables('logAnalyticsName')]",
      "location": "[parameters('location')]",
      "properties": {
        "sku": {
          "name": "PerGB2018"
        },
        "retentionInDays": 30
      }
    },
    {
      "type": "Microsoft.App/managedEnvironments",
      "apiVersion": "2024-03-01",
      "name": "[variables('containerAppEnvName')]",
      "location": "[parameters('location')]",
      "properties": {
        "appLogsConfiguration": {
          "destination": "log-analytics",
          "logAnalyticsConfiguration": {
            "customerId": "[reference(resourceId('Microsoft.OperationalInsights/workspaces', variables('logAnalyticsName')), '2023-09-01').customerId]",
            "sharedKey": "[listKeys(resourceId('Microsoft.OperationalInsights/workspaces', variables('logAnalyticsName')), '2023-09-01').primarySharedKey]"
          }
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.OperationalInsights/workspaces', variables('logAnalyticsName'))]"
      ]
    },
    {
      "type": "Microsoft.App/containerApps",
      "apiVersion": "2024-03-01",
      "name": "[variables('containerAppName')]",
      "location": "[parameters('location')]",
      "identity": {
        "type": "SystemAssigned"
      },
      "properties": {
        "environmentId": "[resourceId('Microsoft.App/managedEnvironments', variables('containerAppEnvName'))]",
        "configuration": {
          "activeRevisionsMode": "Single",
          "ingress": {
            "external": true,
            "targetPort": 8080,
            "transport": "auto",
            "stickySessions": {
              "affinity": "sticky"
            }
          },
          "secrets": [
            {
              "name": "graph-client-secret",
              "keyVaultUrl": "[format('{0}secrets/Graph-ClientSecret', reference(resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName')), '2024-04-01-preview').vaultUri)]",
              "identity": "System"
            },
            {
              "name": "entraid-client-secret",
              "keyVaultUrl": "[format('{0}secrets/EntraId-ClientSecret', reference(resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName')), '2024-04-01-preview').vaultUri)]",
              "identity": "System"
            },
            {
              "name": "connectionstrings-dotmarc",
              "keyVaultUrl": "[format('{0}secrets/ConnectionStrings-DotMarc', reference(resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName')), '2024-04-01-preview').vaultUri)]",
              "identity": "System"
            }
          ]
        },
        "template": {
          "containers": [
            {
              "name": "dotmarc",
              "image": "[parameters('containerImage')]",
              "resources": {
                "cpu": "[json('0.5')]",
                "memory": "1Gi"
              },
              "env": [
                {
                  "name": "Graph__ClientId",
                  "value": "[parameters('graphClientId')]"
                },
                {
                  "name": "Graph__TenantId",
                  "value": "[parameters('graphTenantId')]"
                },
                {
                  "name": "Graph__MailboxAddress",
                  "value": "[parameters('graphMailboxAddress')]"
                },
                {
                  "name": "Graph__TlsrptMailboxAddress",
                  "value": "[parameters('graphTlsrptMailboxAddress')]"
                },
                {
                  "name": "EntraId__TenantId",
                  "value": "[parameters('entraIdTenantId')]"
                },
                {
                  "name": "EntraId__ClientId",
                  "value": "[parameters('entraIdClientId')]"
                },
                {
                  "name": "InitialAdmins__Emails",
                  "value": "[parameters('initialAdminEmails')]"
                },
                {
                  "name": "MtaSts__HostingHostname",
                  "value": "[parameters('mtaStsHostingHostname')]"
                },
                {
                  "name": "MtaSts__Provisioner",
                  "value": "Azure"
                },
                {
                  "name": "MtaSts__AzureSubscriptionId",
                  "value": "[subscription().subscriptionId]"
                },
                {
                  "name": "MtaSts__AzureResourceGroupName",
                  "value": "[resourceGroup().name]"
                },
                {
                  "name": "MtaSts__AzureContainerAppName",
                  "value": "[variables('containerAppName')]"
                },
                {
                  "name": "MtaSts__AzureManagedEnvironmentName",
                  "value": "[variables('containerAppEnvName')]"
                },
                {
                  "name": "KeyVault__VaultUri",
                  "value": "[if(parameters('enableKeyVaultWrite'), reference(resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName')), '2024-04-01-preview').vaultUri, '')]"
                },
                {
                  "name": "Graph__ClientSecret",
                  "secretRef": "graph-client-secret"
                },
                {
                  "name": "EntraId__ClientSecret",
                  "secretRef": "entraid-client-secret"
                },
                {
                  "name": "ConnectionStrings__DotMarc",
                  "secretRef": "connectionstrings-dotmarc"
                }
              ]
            }
          ],
          "scale": {
            "minReplicas": 1,
            "maxReplicas": 1
          }
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.App/managedEnvironments', variables('containerAppEnvName'))]",
        "[resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName'))]"
      ]
    },
    {
      "type": "Microsoft.KeyVault/vaults",
      "apiVersion": "2024-04-01-preview",
      "name": "[variables('keyVaultName')]",
      "location": "[parameters('location')]",
      "properties": {
        "sku": {
          "family": "A",
          "name": "standard"
        },
        "tenantId": "[subscription().tenantId]",
        "enableRbacAuthorization": true
      }
    },
    {
      "type": "Microsoft.Authorization/roleAssignments",
      "apiVersion": "2022-04-01",
      "scope": "[resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName'))]",
      "name": "[guid(resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName')), resourceId('Microsoft.App/containerApps', variables('containerAppName')), 'Key Vault Secrets User')]",
      "properties": {
        "roleDefinitionId": "[subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '4633458b-17de-408a-b874-0445c86b69e6')]",
        "principalId": "[reference(resourceId('Microsoft.App/containerApps', variables('containerAppName')), '2024-03-01', 'full').identity.principalId]",
        "principalType": "ServicePrincipal"
      },
      "dependsOn": [
        "[resourceId('Microsoft.App/containerApps', variables('containerAppName'))]",
        "[resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName'))]"
      ]
    },
    {
      "condition": "[parameters('enableMtaStsHosting')]",
      "type": "Microsoft.Authorization/roleDefinitions",
      "apiVersion": "2022-04-01",
      "name": "[guid(resourceId('Microsoft.App/containerApps', variables('containerAppName')), 'dotMARC MTA-STS Container App Role')]",
      "properties": {
        "roleName": "[format('dotMARC MTA-STS Container App Role ({0})', parameters('baseName'))]",
        "description": "Lets dotMARC bind mta-sts subdomains as custom domains to its own Container App.",
        "type": "CustomRole",
        "permissions": [
          {
            "actions": [
              "Microsoft.App/containerApps/read",
              "Microsoft.App/containerApps/write"
            ],
            "notActions": [],
            "dataActions": [],
            "notDataActions": []
          }
        ],
        "assignableScopes": [
          "[resourceGroup().id]"
        ]
      },
      "dependsOn": [
        "[resourceId('Microsoft.App/containerApps', variables('containerAppName'))]"
      ]
    },
    {
      "condition": "[parameters('enableMtaStsHosting')]",
      "type": "Microsoft.Authorization/roleAssignments",
      "apiVersion": "2022-04-01",
      "scope": "[resourceId('Microsoft.App/containerApps', variables('containerAppName'))]",
      "name": "[guid(resourceId('Microsoft.App/containerApps', variables('containerAppName')), 'dotMARC MTA-STS Container App Role Assignment')]",
      "properties": {
        "roleDefinitionId": "[resourceId('Microsoft.Authorization/roleDefinitions', guid(resourceId('Microsoft.App/containerApps', variables('containerAppName')), 'dotMARC MTA-STS Container App Role'))]",
        "principalId": "[reference(resourceId('Microsoft.App/containerApps', variables('containerAppName')), '2024-03-01', 'full').identity.principalId]",
        "principalType": "ServicePrincipal"
      },
      "dependsOn": [
        "[resourceId('Microsoft.App/containerApps', variables('containerAppName'))]",
        "[resourceId('Microsoft.Authorization/roleDefinitions', guid(resourceId('Microsoft.App/containerApps', variables('containerAppName')), 'dotMARC MTA-STS Container App Role'))]"
      ]
    },
    {
      "condition": "[parameters('enableMtaStsHosting')]",
      "type": "Microsoft.Authorization/roleDefinitions",
      "apiVersion": "2022-04-01",
      "name": "[guid(resourceId('Microsoft.App/managedEnvironments', variables('containerAppEnvName')), 'dotMARC MTA-STS Managed Environment Role')]",
      "properties": {
        "roleName": "[format('dotMARC MTA-STS Managed Environment Role ({0})', parameters('baseName'))]",
        "description": "Lets dotMARC create and read managed certificates on its own Container Apps environment, and join that environment when binding a custom domain, for MTA-STS custom domain hosting.",
        "type": "CustomRole",
        "permissions": [
          {
            "actions": [
              "Microsoft.App/managedEnvironments/read",
              "Microsoft.App/managedEnvironments/join/action",
              "Microsoft.App/managedEnvironments/managedCertificates/read",
              "Microsoft.App/managedEnvironments/managedCertificates/write"
            ],
            "notActions": [],
            "dataActions": [],
            "notDataActions": []
          }
        ],
        "assignableScopes": [
          "[resourceGroup().id]"
        ]
      },
      "dependsOn": [
        "[resourceId('Microsoft.App/managedEnvironments', variables('containerAppEnvName'))]"
      ]
    },
    {
      "condition": "[parameters('enableMtaStsHosting')]",
      "type": "Microsoft.Authorization/roleAssignments",
      "apiVersion": "2022-04-01",
      "scope": "[resourceId('Microsoft.App/managedEnvironments', variables('containerAppEnvName'))]",
      "name": "[guid(resourceId('Microsoft.App/managedEnvironments', variables('containerAppEnvName')), 'dotMARC MTA-STS Managed Environment Role Assignment')]",
      "properties": {
        "roleDefinitionId": "[resourceId('Microsoft.Authorization/roleDefinitions', guid(resourceId('Microsoft.App/managedEnvironments', variables('containerAppEnvName')), 'dotMARC MTA-STS Managed Environment Role'))]",
        "principalId": "[reference(resourceId('Microsoft.App/containerApps', variables('containerAppName')), '2024-03-01', 'full').identity.principalId]",
        "principalType": "ServicePrincipal"
      },
      "dependsOn": [
        "[resourceId('Microsoft.App/containerApps', variables('containerAppName'))]",
        "[resourceId('Microsoft.App/managedEnvironments', variables('containerAppEnvName'))]",
        "[resourceId('Microsoft.Authorization/roleDefinitions', guid(resourceId('Microsoft.App/managedEnvironments', variables('containerAppEnvName')), 'dotMARC MTA-STS Managed Environment Role'))]"
      ]
    },
    {
      "condition": "[parameters('enableKeyVaultWrite')]",
      "type": "Microsoft.Authorization/roleDefinitions",
      "apiVersion": "2022-04-01",
      "name": "[guid(resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName')), 'dotMARC Key Vault Write Role')]",
      "properties": {
        "roleName": "[format('dotMARC Key Vault Write Role ({0})', parameters('baseName'))]",
        "description": "Lets dotMARC write runtime secrets into this Key Vault at runtime.",
        "type": "CustomRole",
        "permissions": [
          {
            "actions": [],
            "notActions": [],
            "dataActions": [
              "Microsoft.KeyVault/vaults/secrets/setSecret/action"
            ],
            "notDataActions": []
          }
        ],
        "assignableScopes": [
          "[resourceGroup().id]"
        ]
      },
      "dependsOn": [
        "[resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName'))]"
      ]
    },
    {
      "condition": "[parameters('enableKeyVaultWrite')]",
      "type": "Microsoft.Authorization/roleAssignments",
      "apiVersion": "2022-04-01",
      "scope": "[resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName'))]",
      "name": "[guid(resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName')), resourceId('Microsoft.App/containerApps', variables('containerAppName')), 'dotMARC Key Vault Write Role Assignment')]",
      "properties": {
        "roleDefinitionId": "[resourceId('Microsoft.Authorization/roleDefinitions', guid(resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName')), 'dotMARC Key Vault Write Role'))]",
        "principalId": "[reference(resourceId('Microsoft.App/containerApps', variables('containerAppName')), '2024-03-01', 'full').identity.principalId]",
        "principalType": "ServicePrincipal"
      },
      "dependsOn": [
        "[resourceId('Microsoft.App/containerApps', variables('containerAppName'))]",
        "[resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName'))]",
        "[resourceId('Microsoft.Authorization/roleDefinitions', guid(resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName')), 'dotMARC Key Vault Write Role'))]"
      ]
    },
    {
      "type": "Microsoft.KeyVault/vaults/secrets",
      "apiVersion": "2024-04-01-preview",
      "name": "[format('{0}/{1}', variables('keyVaultName'), 'Graph-ClientSecret')]",
      "properties": {
        "value": ""
      },
      "dependsOn": [
        "[resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName'))]"
      ]
    },
    {
      "type": "Microsoft.KeyVault/vaults/secrets",
      "apiVersion": "2024-04-01-preview",
      "name": "[format('{0}/{1}', variables('keyVaultName'), 'EntraId-ClientSecret')]",
      "properties": {
        "value": ""
      },
      "dependsOn": [
        "[resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName'))]"
      ]
    },
    {
      "type": "Microsoft.KeyVault/vaults/secrets",
      "apiVersion": "2024-04-01-preview",
      "name": "[format('{0}/{1}', variables('keyVaultName'), 'ConnectionStrings-DotMarc')]",
      "properties": {
        "value": ""
      },
      "dependsOn": [
        "[resourceId('Microsoft.KeyVault/vaults', variables('keyVaultName'))]"
      ]
    }
  ],
  "outputs": {
    "containerAppUrl": {
      "type": "string",
      "value": "[format('https://{0}', reference(resourceId('Microsoft.App/containerApps', variables('containerAppName')), '2024-03-01').configuration.ingress.fqdn)]"
    },
    "containerAppName": {
      "type": "string",
      "value": "[variables('containerAppName')]"
    },
    "postgresServerFqdn": {
      "type": "string",
      "value": "[reference(resourceId('Microsoft.DBforPostgreSQL/flexibleServers', variables('postgresServerName')), '2024-08-01').fullyQualifiedDomainName]"
    },
    "keyVaultName": {
      "type": "string",
      "value": "[variables('keyVaultName')]"
    }
  }
}