name: "Deploy - sqlsecrot (Bicep)"

# run manually
on:
  workflow_dispatch:

# Set envs
env:
  WORKDIR: "support/sqlsecretrotation/iac/bicep"
  RESOURCES_SUFFIX: "sqlsecrot"
  # RESOURCES_PREFIX: "devopsoh44707" # hardcoded or dynamic based on repo name
  # LOCATION: "westus2" # hardcoded or get from secrets

# Set defaults for GitHub Actions runner
defaults:
  run:
    working-directory: "support/sqlsecretrotation/iac/bicep"

jobs:
  deploy:
    name: "Deploy"
    runs-on: ubuntu-latest

    steps:
      # Checkout the repository to the GitHub Actions runner
      - name: Checkout
        uses: actions/checkout@v2

      # Get RESOURCES_PREFIX based on the repo name
      - name: Get repo name
        uses: actions/github-script@v5
        id: resources_prefix
        with:
          result-encoding: string
          script: return context.repo.repo.toLowerCase()

      # Concat RG name
      - name: Get resource group name
        uses: actions/github-script@v5
        id: resource_group_name
        with:
          result-encoding: string
          script: |
            const { RESOURCES_SUFFIX } = process.env
            const repo_name = "${{ steps.resources_prefix.outputs.result }}"
            return `${repo_name}${RESOURCES_SUFFIX}rg`

      # Login to Azure with Service Principal
      - name: "Azure Login"
        uses: Azure/login@v1
        with:
          creds: ${{ secrets.AZURE_CREDENTIALS }}

      # Deploy
      - name: "Deploy"
        uses: Azure/cli@1.0.4
        with:
          inlineScript: |
            if [ $(az group exists --name ${{ steps.resource_group_name.outputs.result }}) = false ]; then
              az group create --name ${{ steps.resource_group_name.outputs.result }} --location ${{ secrets.LOCATION }}
            fi
            az deployment group create \
            --name ${{ github.run_id }} \
            --resource-group ${{ steps.resource_group_name.outputs.result }} \
            --template-file ${{ env.WORKDIR }}/main.bicep \
            --parameters keyVaultRgName='${{ steps.resources_prefix.outputs.result }}rg' keyVaultName='${{ steps.resources_prefix.outputs.result }}kv' resourcesPrefix='${{ steps.resources_prefix.outputs.result }}' resourcesSuffix='${{ env.RESOURCES_SUFFIX }}'
