name: OpenTofu K8S Apps apply

on:
  push:
    branches:
      - main
    paths:
      - "terraform/apps/contabo/**"
jobs:
  iac-apply:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup environment
        uses: ./.github/actions/setup-env

      - name: Setup Ansible Environment
        id: setup_ansible_env
        uses: ./.github/actions/setup-ansible-env
        with:
          project-id: ${{ secrets.BW_PROJECT_ID }}
          organization-id: ${{ secrets.BW_ORGANIZATION_ID }}
          access-token: ${{ secrets.BW_ACCESS_TOKEN }}
          ansible-user: ${{ secrets.ANSIBLE_USER }}
          host-group: microk8s

      - name: Setup OpenTofu Environment
        uses: ./.github/actions/setup-opentofu-env

      - name: Setup Kubernetes Environment
        uses: ./.github/actions/setup-k8s-env
        with:
          host: prod-01.alexpires.me
          project-id: ${{ secrets.BW_PROJECT_ID }}
          organization-id: ${{ secrets.BW_ORGANIZATION_ID }}
          access-token: ${{ secrets.BW_ACCESS_TOKEN }}
          ansible-user: ${{ secrets.ANSIBLE_USER }}

      - name: OpenTofu Init and Apply
        env:
          BW_PROJECT_ID: ${{ secrets.BW_PROJECT_ID }}
          BW_ORGANIZATION_ID: ${{ secrets.BW_ORGANIZATION_ID }}
          BW_ACCESS_TOKEN: ${{ secrets.BW_ACCESS_TOKEN }}
          ANSIBLE_USER: ${{ secrets.ANSIBLE_USER }}
          SSH_AUTH_SOCK: ${{ steps.setup_ansible_env.outputs.ssh-auth-sock }}
        run: |
          cd terraform/k8sapps
          sectool -f ../../sectool.json exec tofu init
          sectool -f ../../sectool.json exec tofu apply --auto-approve
