name: Infrastructure

on:
  push:
    branches: [main]
    tags: ['v*']
    paths: ['infra/**']
  pull_request:
    branches: [main]
    paths: ['infra/**']

jobs:
  plan:
    runs-on: docker
    steps:
      - uses: actions/checkout@v4

      - name: Setup OpenTofu
        uses: opentofu/setup-opentofu@v1

      - name: Set environment target
        id: target
        run: |
          if [[ "${{ github.ref }}" == refs/tags/v* ]]; then
            echo "env_name=production" >> $GITHUB_OUTPUT
          else
            echo "env_name=staging" >> $GITHUB_OUTPUT
          fi

      - name: Init and Plan
        working-directory: infra
        env:
          HCLOUD_TOKEN: ${{ secrets.HCLOUD_TOKEN }}
          ENV_NAME: ${{ steps.target.outputs.env_name }}
          TF_VAR_hcloud_token: ${{ secrets.HCLOUD_TOKEN }}
          TF_VAR_ssh_public_key: ${{ secrets.SSH_PUBLIC_KEY }}
          TF_VAR_domain: "holo-grid.bar"
          TF_VAR_forgejo_domain: "git.holo-grid.bar"
        run: |
          tofu init
          tofu workspace select $ENV_NAME || tofu workspace new $ENV_NAME
          tofu plan -out=tfplan

      - name: Upload plan artifact
        if: github.event_name == 'pull_request'
        uses: actions/upload-artifact@v4
        with:
          name: tfplan
          path: infra/tfplan

  apply:
    runs-on: docker
    needs: plan
    if: (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) && github.event_name == 'push'
    steps:
      - uses: actions/checkout@v4

      - name: Setup OpenTofu
        uses: opentofu/setup-opentofu@v1

      - name: Set environment target
        id: target
        run: |
          if [[ "${{ github.ref }}" == refs/tags/v* ]]; then
            echo "env_name=production" >> $GITHUB_OUTPUT
          else
            echo "env_name=staging" >> $GITHUB_OUTPUT
          fi

      - name: Init and Apply
        working-directory: infra
        env:
          HCLOUD_TOKEN: ${{ secrets.HCLOUD_TOKEN }}
          ENV_NAME: ${{ steps.target.outputs.env_name }}
          TF_VAR_hcloud_token: ${{ secrets.HCLOUD_TOKEN }}
          TF_VAR_ssh_public_key: ${{ secrets.SSH_PUBLIC_KEY }}
          TF_VAR_domain: "holo-grid.bar"
          TF_VAR_forgejo_domain: "git.holo-grid.bar"
        run: |
          tofu init
          tofu workspace select $ENV_NAME || tofu workspace new $ENV_NAME
          tofu apply -auto-approve
