name: Tests

on:
  push:
    branches: ["main"]
  pull_request:

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  complement:
    runs-on: ubuntu-latest
    steps:
      # Env vars are set file a file given by $GITHUB_PATH. We need both Go 1.17 and GOPATH on env to run Complement.
      # See https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#adding-a-system-path
      - name: "Set Go Version"
        run: |
          echo "$GOROOT_1_17_X64/bin" >> $GITHUB_PATH
          echo "~/go/bin" >> $GITHUB_PATH

      - name: "Install Complement Dependencies"
        # We don't need to install Go because it is included on the Ubuntu 20.04 image:
        # See https://github.com/actions/virtual-environments/blob/main/images/linux/Ubuntu2004-Readme.md specifically GOROOT_1_17_X64
        run: |
          sudo apt-get update && sudo apt-get install -y libolm3 libolm-dev
          go get -v github.com/haveyoudebuggedit/gotestfmt/v2/cmd/gotestfmt@latest

      - name: Run actions/checkout@v2 for dendrite
        uses: actions/checkout@v2
        with:
          path: dendrite

      # Attempt to check out the same branch of Complement as the PR. If it
      # doesn't exist, fallback to main.
      - name: Checkout complement
        shell: bash
        run: |
          mkdir -p complement
          # Attempt to use the version of complement which best matches the current
          # build. Depending on whether this is a PR or release, etc. we need to
          # use different fallbacks.
          #
          # 1. First check if there's a similarly named branch (GITHUB_HEAD_REF
          #    for pull requests, otherwise GITHUB_REF).
          # 2. Attempt to use the base branch, e.g. when merging into release-vX.Y
          #    (GITHUB_BASE_REF for pull requests).
          # 3. Use the default complement branch ("master").
          for BRANCH_NAME in "$GITHUB_HEAD_REF" "$GITHUB_BASE_REF" "${GITHUB_REF#refs/heads/}" "master"; do
            # Skip empty branch names and merge commits.
            if [[ -z "$BRANCH_NAME" || $BRANCH_NAME =~ ^refs/pull/.* ]]; then
              continue
            fi

            (wget -O - "https://github.com/matrix-org/complement/archive/$BRANCH_NAME.tar.gz" | tar -xz --strip-components=1 -C complement) && break
          done

      # Build initial Dendrite image
      - run: docker build -t complement-dendrite -f build/scripts/Complement.Dockerfile .
        working-directory: dendrite

      # Run Complement
      - run: |
          set -o pipefail &&
          go test -v -json -tags dendrite_blacklist ./tests/... 2>&1 | gotestfmt
        shell: bash
        name: Run Complement Tests
        env:
          COMPLEMENT_BASE_IMAGE: complement-dendrite:latest
        working-directory: complement