# Xplorr Terraform cost estimate for GitHub Actions
#
# On every pull request that changes Terraform, this workflow posts the
# monthly cost change as a comment and keeps the estimate in Xplorr
# (Cost Estimate > Pull requests). When the pull request merges, Xplorr
# compares the estimate with what the resources actually bill.
#
# Setup, in the GitHub repository that holds your Terraform:
#
#   1. In Xplorr, open Settings > API Tokens and create a token. The token
#      must belong to a member or admin for estimates to be kept.
#
#   2. In GitHub, Settings > Secrets and variables > Actions:
#        Secret   XPLORR_API_TOKEN  the token from step 1
#        Variable XPLORR_URL        your console address, for example
#                                   https://console.xplorr.io
#
#   3. Give the workflow read access to AWS so Terraform can plan. This file
#      assumes an IAM role through GitHub OIDC: save its ARN as the secret
#      AWS_PLAN_ROLE_ARN. Change the configure-aws-credentials step if you
#      sign in another way.
#
#   4. Save this file in the repository as
#      .github/workflows/terraform-cost-estimate.yml and set TF_DIR below to
#      the folder that holds your Terraform root module (AWS_REGION too).
#
#   5. Optional: if the console sits behind Cloudflare Access, create an
#      Access service token and save CF_ACCESS_CLIENT_ID and
#      CF_ACCESS_CLIENT_SECRET as secrets.
#
#   6. Open a pull request that changes a .tf or .tfvars file. The estimate
#      appears as a comment and in Xplorr.
#
# What is priced: AWS on demand list prices for aws_instance,
# aws_db_instance, aws_ebs_volume, aws_nat_gateway, aws_lb and
# aws_elasticache_cluster. Other resources are listed as not estimated.
#
# Give created resources a Name tag: it is how Xplorr finds an instance, NAT
# gateway or load balancer in its inventory after apply, to compare the
# estimate with billing from 7 complete days after the merge.

name: Terraform cost estimate

on:
  pull_request:
    types: [opened, synchronize, reopened, closed]
    paths:
      - "**/*.tf"
      - "**/*.tfvars"

permissions:
  contents: read
  id-token: write
  pull-requests: write

jobs:
  estimate:
    if: github.event.action != 'closed'
    runs-on: ubuntu-latest
    env:
      TF_DIR: infra
      AWS_REGION: us-east-1
      XPLORR_URL: ${{ vars.XPLORR_URL }}
    steps:
      - uses: actions/checkout@v7.0.1

      - uses: aws-actions/configure-aws-credentials@v5
        with:
          role-to-assume: ${{ secrets.AWS_PLAN_ROLE_ARN }}
          aws-region: ${{ env.AWS_REGION }}

      - uses: hashicorp/setup-terraform@v4.0.1
        with:
          terraform_wrapper: false

      - name: Terraform plan as JSON
        working-directory: ${{ env.TF_DIR }}
        run: |
          terraform init -input=false
          terraform plan -input=false -lock=false -out=plan.out
          terraform show -json plan.out > "$RUNNER_TEMP/plan.json"

      - name: Request estimate from Xplorr
        env:
          XPLORR_API_TOKEN: ${{ secrets.XPLORR_API_TOKEN }}
          CF_ACCESS_CLIENT_ID: ${{ secrets.CF_ACCESS_CLIENT_ID }}
          CF_ACCESS_CLIENT_SECRET: ${{ secrets.CF_ACCESS_CLIENT_SECRET }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          PR_SHA: ${{ github.event.pull_request.head.sha }}
        run: |
          set -euo pipefail
          cf=()
          if [ -n "${CF_ACCESS_CLIENT_ID:-}" ]; then
            cf=(-H "CF-Access-Client-Id: $CF_ACCESS_CLIENT_ID" -H "CF-Access-Client-Secret: $CF_ACCESS_CLIENT_SECRET")
          fi

          # Exchange the long lived API token for a short lived access token
          jwt=$(curl -fsS -X POST "${cf[@]}" -H "Authorization: Bearer $XPLORR_API_TOKEN" \
            "$XPLORR_URL/api/auth/tokens/exchange" | jq -r .accessToken)

          node -e '
            const fs = require("fs");
            const dir = process.env.RUNNER_TEMP;
            const plan = JSON.parse(fs.readFileSync(dir + "/plan.json", "utf8"));
            const pr = { repo: process.env.GITHUB_REPOSITORY, number: Number(process.env.PR_NUMBER), commit: process.env.PR_SHA };
            fs.writeFileSync(dir + "/body.json", JSON.stringify({ plan, region: process.env.AWS_REGION, pr }));
          '

          curl -fsS -X POST "${cf[@]}" \
            -H "Authorization: Bearer $jwt" \
            -H "Content-Type: application/json" \
            -d @"$RUNNER_TEMP/body.json" \
            "$XPLORR_URL/api/opt/estimate?format=markdown" > "$RUNNER_TEMP/estimate.md"

      - name: Comment on the pull request
        uses: actions/github-script@v9.0.0
        with:
          script: |
            const fs = require('fs');
            const marker = '_Posted by the Xplorr cost estimate workflow._';
            const body = fs.readFileSync(`${process.env.RUNNER_TEMP}/estimate.md`, 'utf8') + `\n\n${marker}`;
            const { owner, repo } = context.repo;
            const issue_number = context.issue.number;
            const comments = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
            const existing = comments.find(c => c.body && c.body.includes(marker));
            if (existing) {
              await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
            } else {
              await github.rest.issues.createComment({ owner, repo, issue_number, body });
            }

  # Tells Xplorr the pull request merged, so its estimate can be compared
  # with actual billing. Needs no cloud credentials.
  merged:
    if: github.event.action == 'closed' && github.event.pull_request.merged
    runs-on: ubuntu-latest
    env:
      XPLORR_URL: ${{ vars.XPLORR_URL }}
    steps:
      - name: Report the merge to Xplorr
        env:
          XPLORR_API_TOKEN: ${{ secrets.XPLORR_API_TOKEN }}
          CF_ACCESS_CLIENT_ID: ${{ secrets.CF_ACCESS_CLIENT_ID }}
          CF_ACCESS_CLIENT_SECRET: ${{ secrets.CF_ACCESS_CLIENT_SECRET }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          MERGED_AT: ${{ github.event.pull_request.merged_at }}
        run: |
          set -euo pipefail
          cf=()
          if [ -n "${CF_ACCESS_CLIENT_ID:-}" ]; then
            cf=(-H "CF-Access-Client-Id: $CF_ACCESS_CLIENT_ID" -H "CF-Access-Client-Secret: $CF_ACCESS_CLIENT_SECRET")
          fi
          jwt=$(curl -fsS -X POST "${cf[@]}" -H "Authorization: Bearer $XPLORR_API_TOKEN" \
            "$XPLORR_URL/api/auth/tokens/exchange" | jq -r .accessToken)
          body=$(jq -n --arg repo "$GITHUB_REPOSITORY" --argjson number "$PR_NUMBER" --arg merged_at "$MERGED_AT" \
            '{repo: $repo, number: $number, merged_at: $merged_at}')
          # 404 means no estimate was kept for this pull request; nothing to do
          code=$(curl -sS -o /dev/null -w '%{http_code}' -X POST "${cf[@]}" \
            -H "Authorization: Bearer $jwt" -H "Content-Type: application/json" \
            -d "$body" "$XPLORR_URL/api/opt/estimate/pull-requests/merged")
          case "$code" in 200|404) echo "Xplorr answered $code" ;; *) echo "Xplorr answered $code"; exit 1 ;; esac
