invario-review:
  timeout: 55 minutes
  variables:
    GIT_STRATEGY: none
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_SOURCE_PROJECT_ID == $CI_PROJECT_ID'
    - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH && $CI_COMMIT_BEFORE_SHA !~ /^0+$/'
  script:
    - |
      set -eu
      if [ "${CI_PIPELINE_SOURCE:-}" = merge_request_event ]; then
        BASE_SHA=$CI_MERGE_REQUEST_DIFF_BASE_SHA
        HEAD_SHA=${CI_MERGE_REQUEST_SOURCE_BRANCH_SHA:-$CI_COMMIT_SHA}
      else
        BASE_SHA=$CI_COMMIT_BEFORE_SHA
        HEAD_SHA=$CI_COMMIT_SHA
      fi
      REQUEST_KEY=gl-$CI_PROJECT_ID-$CI_JOB_ID
      api="${INVARIO_URL%/}/v1/reviews"
      body=$(jq -nc --arg base "$BASE_SHA" --arg head "$HEAD_SHA" '{base:$base,head:$head}')
      if [ -n "${INVARIO_RECEIPTS_FILE:-}" ]; then
        body=$(printf '%s' "$body" | jq -ec --slurpfile evidence "$INVARIO_RECEIPTS_FILE" 'if ($evidence|length)==1 and ($evidence[0]|type)=="object" and $evidence[0].base==.base and $evidence[0].repositories.primary==.head then . + {receipts:$evidence[0]} else error("Expected one Invario receipt matching the requested commits") end')
      fi
      auth="Authorization: Bearer $INVARIO_CI_TOKEN"
      reply=$(printf '%s' "$body" | curl -fsS --max-time 30 --retry 2 -H "$auth" -H "Idempotency-Key: $REQUEST_KEY" \
        -H "X-Invario-Receipts-Token: ${INVARIO_CI_RECEIPTS_TOKEN:-}" \
        -H 'Content-Type: application/json' --data-binary @- "$api")
      id=$(printf '%s' "$reply" | jq -er '.id | select(test("^[0-9a-f]{32}$"))')
      echo "Invario review $id"
      while :; do
        reply=$(curl -fsS --max-time 30 --retry 2 -H "$auth" "$api/$id")
        status=$(printf '%s' "$reply" | jq -er '.status')
        case "$status" in
          completed)
            printf '%s' "$reply" | jq -e '.report' > invario-report.json
            jq -er '.review_verdict' invario-report.json
            if [ "${INVARIO_REVIEW_GATE:-}" = 1 ]; then
              if ! jq -e --arg base "$BASE_SHA" --arg head "$HEAD_SHA" \
                '.base == $base and .repositories.primary == $head and .evidence.status == "complete" and .review_verdict == "pass"' \
                invario-report.json >/dev/null; then
                echo "Invario gate requires a complete passing report for $BASE_SHA..$HEAD_SHA" >&2
                exit 1
              fi
            fi
            break ;;
          queued|running) sleep 2 ;;
          *) echo "Review $id ended with status $status" >&2; exit 1 ;;
        esac
      done
  artifacts:
    when: always
    paths: [invario-report.json]
