name: OpenTofu Automation

on:
  push:
    branches:
      - main
    paths:
      - 'terraform/**'
  workflow_dispatch:

jobs:
  deploy:
    runs-on: docker
    container:
      image: mafyuh/ansible-bws:v1.1.1
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Get Secrets from Bitwarden
        id: bitwarden-secrets
        uses: https://github.com/bitwarden/sm-action@v2
        with:
          access_token: ${{ secrets.BW_ACCESS_TOKEN }}
          base_url: https://vault.bitwarden.com
          secrets: |
            2dae51bd-bd65-474c-971c-b20800f22afa > aws_access_key_id
            287c852d-f2b5-467d-bfc4-b20800f25f52 > aws_secret_access_key
            3b222376-ccd9-4f44-a4b4-b222001af68a > grafana_auth
            030fbb6a-3b6d-40dc-9c26-b222001b0fb6 > grafana_url
            f8f85ab2-5f6d-46a7-9e06-b20800076d26 > s3_endpoint
            b6dac092-df23-4e28-8449-b2770059096d > kube_config
            4dff237e-93ad-4eda-a776-b28400653181 > bws_access_token

      
      - name: Create tfvars file
        working-directory: ./terraform
        run: |
          cat <<EOF > terraform.tfvars
          aws_access_key_id = "${{ steps.bitwarden-secrets.outputs.aws_access_key_id }}"
          aws_secret_access_key = "${{ steps.bitwarden-secrets.outputs.aws_secret_access_key }}"
          grafana_auth = "${{ steps.bitwarden-secrets.outputs.grafana_auth }}"
          grafana_url = "${{ steps.bitwarden-secrets.outputs.grafana_url }}"
          s3_endpoint = "${{ steps.bitwarden-secrets.outputs.s3_endpoint }}"
          access_token = "${{ steps.bitwarden-secrets.outputs.bws_access_token }}"
          EOF

      - name: Make Kube directory
        run: |
          mkdir ~/.kube

      - name: Create Kube Config
        run: |
          printf "%s" "${{ steps.bitwarden-secrets.outputs.kube_config }}" > ~/.kube/config

      - name: Setup OpenTofu
        uses: https://github.com/opentofu/setup-opentofu@v1.0.5

      - name: Run OpenTofu Init
        working-directory: ./terraform
        env:
          AWS_ACCESS_KEY_ID: ${{ steps.bitwarden-secrets.outputs.aws_access_key_id }}
          AWS_SECRET_ACCESS_KEY: ${{ steps.bitwarden-secrets.outputs.aws_secret_access_key }}
        run: |
          tofu init -var-file=terraform.tfvars


      - name: Run OpenTofu Plan
        id: plan
        working-directory: ./terraform
        env:
          AWS_ACCESS_KEY_ID: ${{ steps.bitwarden-secrets.outputs.aws_access_key_id }}
          AWS_SECRET_ACCESS_KEY: ${{ steps.bitwarden-secrets.outputs.aws_secret_access_key }}
        run: tofu plan -parallelism=1 -out=tfplan

      - name: Apply the Plan
        if: success()
        working-directory: ./terraform
        env:
          AWS_ACCESS_KEY_ID: ${{ steps.bitwarden-secrets.outputs.aws_access_key_id }}
          AWS_SECRET_ACCESS_KEY: ${{ steps.bitwarden-secrets.outputs.aws_secret_access_key }}
        run: tofu apply tfplan