---
parameters:
  - name: serviceConnection
  - name: backendAzureResourceGroupName
  - name: backendAzureStorageAccountName
  - name: backendAzureStorageAccountContainerName
  - name: backendAzureStorageAccountContainerKeyName
    default: terraform.tfstate
  - name: root_module_folder_relative_path
    default: '.'

steps:
  - task: AzureCLI@2
    displayName: 'Terraform Init'
    inputs:
      azureSubscription: $${{ parameters.serviceConnection }}
      scriptType: pscore
      scriptLocation: inlineScript
      addSpnToEnvironment: true
      inlineScript: |
        # Get settings from service connection
        az account show 2>$null | ConvertFrom-Json | Set-Variable account
        $clientId = $account.user.name
        $oidcToken = $env:idToken # requires addSpnToEnvironment: true
        $subscriptionId = $account.id
        $tenantId = $account.tenantId

        $env:ARM_TENANT_ID = $tenantId
        $env:ARM_SUBSCRIPTION_ID = $subscriptionId
        $env:ARM_OIDC_TOKEN = $oidcToken
        $env:ARM_USE_OIDC = "true"
        $env:ARM_CLIENT_ID = $clientId
        $env:ARM_USE_AZUREAD = "true"

        $arguments = @()
        $arguments += "-chdir=$${{ parameters.root_module_folder_relative_path }}"
        $arguments += "init"
        $arguments += "-backend-config=storage_account_name=$($env:BACKEND_AZURE_STORAGE_ACCOUNT_NAME)"
        $arguments += "-backend-config=container_name=$($env:BACKEND_AZURE_STORAGE_ACCOUNT_CONTAINER_NAME)"
        $arguments += "-backend-config=key=$($env:BACKEND_AZURE_STORAGE_ACCOUNT_CONTAINER_KEY_NAME)"
        $arguments += "-backend-config=resource_group_name=$($env:BACKEND_AZURE_RESOURCE_GROUP_NAME)"

        # Run terraform init
        $command = "terraform"
        Write-Host "Running: $command $arguments"
        & $command $arguments

    env:
      BACKEND_AZURE_RESOURCE_GROUP_NAME: $${{ parameters.backendAzureResourceGroupName }}
      BACKEND_AZURE_STORAGE_ACCOUNT_NAME: $${{ parameters.backendAzureStorageAccountName }}
      BACKEND_AZURE_STORAGE_ACCOUNT_CONTAINER_NAME: $${{ parameters.backendAzureStorageAccountContainerName }}
      BACKEND_AZURE_STORAGE_ACCOUNT_CONTAINER_KEY_NAME: $${{ parameters.backendAzureStorageAccountContainerKeyName }}
