{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "location": {
            "defaultValue": "[resourceGroup().location]",
            "type": "String",
            "metadata": {
                "description": "Azure region where all resources will be deployed. Defaults to the resource group's location."
            }
        },
        "adminUsername": {
            "defaultValue": "ubuntu",
            "type": "String",
            "metadata": {
                "description": "Admin username for the virtual machine scale set instances."
            }
        },
        "authenticationType": {
            "defaultValue": "sshPublicKey",
            "allowedValues": [
                "sshPublicKey",
                "password"
            ],
            "type": "String",
            "metadata": {
                "description": "Authentication method for VM login. Use sshPublicKey for key-based authentication or password for password-based login."
            }
        },
        "adminPasswordOrKey": {
            "type": "SecureString",
            "metadata": {
                "description": "SSH public key (if sshPublicKey is selected) or admin password (if password authentication is selected)."
            }
        },
        "vmSku": {
            "defaultValue": "Standard_D4s_v5",
            "type": "String",
            "metadata": {
                "description": "Azure VM size (SKU) to be used for the Virtual Machine Scale Set instances."
            }
        },
        "vmssName": {
            "minLength": 3,
            "maxLength": 61,
            "type": "String",
            "metadata": {
                "description": "Name of the Virtual Machine Scale Set. This will also be used as the computer name prefix."
            }
        },
        "posthogDomain": {
            "type": "String",
            "metadata": {
                "description": "Public domain name that will be used to access the PostHog application (e.g., posthog.example.com)."
            }
        },
        "posthogTag": {
            "defaultValue": "latest",
            "type": "String",
            "metadata": {
                "description": "PostHog Docker image tag to deploy (e.g., latest, v1.123.0)."
            }
        },
        "dataDiskSizeGB": {
            "defaultValue": 100,
            "type": "Int",
            "metadata": {
                "description": "Size in GB of the OS disk attached to each VM instance."
            }
        },
        "enableSpot": {
            "defaultValue": true,
            "type": "Bool",
            "metadata": {
                "description": "Enable Azure Spot instances to reduce cost. Spot VMs may be evicted at any time."
            }
        },
        "existingVnetResourceGroupName": {
            "type": "String",
            "metadata": {
                "description": "Name of the resource group that contains the existing Virtual Network."
            }
        },
        "existingVnetName": {
            "type": "String",
            "metadata": {
                "description": "Name of the existing Virtual Network where the VMSS will be deployed."
            }
        },
        "existingSubnetName": {
            "type": "String",
            "metadata": {
                "description": "Name of the subnet within the existing Virtual Network used by the VMSS."
            }
        }
    },
    "variables": {
        "nsgName": "posthog-nsg",
        "subnetId": "[resourceId(parameters('existingVnetResourceGroupName'), 'Microsoft.Network/virtualNetworks/subnets', parameters('existingVnetName'), parameters('existingSubnetName'))]"
    },
    "resources": [
        {
            "type": "Microsoft.Network/networkSecurityGroups",
            "apiVersion": "2023-09-01",
            "name": "[variables('nsgName')]",
            "location": "[parameters('location')]",
            "properties": {
                "securityRules": [
                    {
                        "name": "Allow-SSH",
                        "properties": {
                            "priority": 1000,
                            "protocol": "Tcp",
                            "access": "Allow",
                            "direction": "Inbound",
                            "sourceAddressPrefix": "*",
                            "sourcePortRange": "*",
                            "destinationAddressPrefix": "*",
                            "destinationPortRange": "22"
                        }
                    },
                    {
                        "name": "Allow-HTTP",
                        "properties": {
                            "priority": 1010,
                            "protocol": "Tcp",
                            "access": "Allow",
                            "direction": "Inbound",
                            "sourceAddressPrefix": "*",
                            "sourcePortRange": "*",
                            "destinationAddressPrefix": "*",
                            "destinationPortRange": "80"
                        }
                    },
                    {
                        "name": "Allow-HTTPS",
                        "properties": {
                            "priority": 1020,
                            "protocol": "Tcp",
                            "access": "Allow",
                            "direction": "Inbound",
                            "sourceAddressPrefix": "*",
                            "sourcePortRange": "*",
                            "destinationAddressPrefix": "*",
                            "destinationPortRange": "443"
                        }
                    }
                ]
            }
        },
        {
            "type": "Microsoft.Compute/virtualMachineScaleSets",
            "apiVersion": "2023-03-01",
            "name": "[parameters('vmssName')]",
            "location": "[parameters('location')]",
            "dependsOn": [
                "[resourceId('Microsoft.Network/networkSecurityGroups', variables('nsgName'))]"
            ],
            "sku": {
                "name": "[parameters('vmSku')]",
                "capacity": 1
            },
            "properties": {
                "overprovision": true,
                "upgradePolicy": {
                    "mode": "Manual"
                },
                "virtualMachineProfile": {
                    "priority": "[if(parameters('enableSpot'), 'Spot', 'Regular')]",
                    "evictionPolicy": "[if(parameters('enableSpot'), 'Delete', json('null'))]",
                    "billingProfile": "[if(parameters('enableSpot'), json('{\"maxPrice\": -1}'), json('null'))]",
                    "storageProfile": {
                        "imageReference": {
                            "publisher": "Canonical",
                            "offer": "ubuntu-24_04-lts",
                            "sku": "server",
                            "version": "latest"
                        },
                        "osDisk": {
                            "createOption": "FromImage",
                            "diskSizeGB": "[parameters('dataDiskSizeGB')]",
                            "managedDisk": {
                                "storageAccountType": "Premium_LRS"
                            }
                        }
                    },
                    "osProfile": {
                        "computerNamePrefix": "[parameters('vmssName')]",
                        "adminUsername": "[parameters('adminUsername')]",
                        "linuxConfiguration": {
                            "disablePasswordAuthentication": "[equals(parameters('authenticationType'), 'sshPublicKey')]",
                            "ssh": {
                                "publicKeys": [
                                    {
                                        "path": "[format('/home/{0}/.ssh/authorized_keys', parameters('adminUsername'))]",
                                        "keyData": "[if(equals(parameters('authenticationType'), 'sshPublicKey'), parameters('adminPasswordOrKey'), json('null'))]"
                                    }
                                ]
                            }
                        },
                        "adminPassword": "[if(equals(parameters('authenticationType'), 'password'), parameters('adminPasswordOrKey'), json('null'))]",
                        "customData": "[base64(concat('#cloud-config\n','package_update: true\n','packages:\n',' - docker.io\n',' - docker-compose-v2\n','runcmd:\n',' - usermod -aG docker ', parameters('adminUsername'), '\n',' - mkdir -p /opt/posthog\n',' - cd /opt/posthog\n',' - curl -fsSL https://raw.githubusercontent.com/posthog/posthog/HEAD/bin/deploy-hobby | bash -s -- ', parameters('posthogTag'), ' ', parameters('posthogDomain'), '\n'))]"
                    },
                    "networkProfile": {
                        "networkInterfaceConfigurations": [
                            {
                                "name": "vmss-nic",
                                "properties": {
                                    "primary": true,
                                    "networkSecurityGroup": {
                                        "id": "[resourceId('Microsoft.Network/networkSecurityGroups', variables('nsgName'))]"
                                    },
                                    "ipConfigurations": [
                                        {
                                            "name": "ipconfig",
                                            "properties": {
                                                "subnet": {
                                                    "id": "[variables('subnetId')]"
                                                },
                                                "primary": true,
                                                "publicIPAddressConfiguration": {
                                                    "name": "vmss-public-ip",
                                                    "properties": {
                                                        "idleTimeoutInMinutes": 15
                                                    }
                                                }
                                            }
                                        }
                                    ]
                                }
                            }
                        ]
                    }
                }
            }
        }
    ]
}