name: OLM-Tests

on:
  push:
    branches: [ master, release-0.* ]
  pull_request:
    branches: [ master, release-0.* ]

jobs:
  main:
    name: Run tests
    runs-on: ubuntu-20.04

    steps:
    - uses: actions/checkout@v2
      with:
        fetch-depth: 0 # Fetch all history for all tags and branches

    # https://github.com/mvdan/github-actions-golang#how-do-i-set-up-caching-between-builds
    - uses: actions/cache@v2
      with:
        # In order:
        # * Module download cache
        # * Build cache (Linux)
        path: |
          ~/go/pkg/mod
          ~/.cache/go-build
        key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
        restore-keys: |
          ${{ runner.os }}-go-

    - uses: actions/setup-go@v2
      with:
        go-version: '1.16'

    - name: Download binaries
      run: |
        mkdir -p ${GITHUB_WORKSPACE}/bin
        echo "${GITHUB_WORKSPACE}/bin" >> ${GITHUB_PATH}
        make download-binaries

    - name: Verify bundle
      run: |
        make bundle
        git diff --exit-code

    - name: Create and set up K8s KinD Cluster
      run: |
        export KIND_IMG_TAG=v1.21.1@sha256:69860bda5563ac81e3c0057d654b5253219618a22ec3a346306239bba8cfa1a6
        ./scripts/kind-with-registry.sh

    - name: Build and Push Test Container Image and Bundle/Bundle Index Images
      run: |
        # TODO: Use operator-sdk run bundle and bundle-upgrade commands for
        # testing with OLM.
        PREV_BUNDLE_INDEX_IMG_VERSION=$(make prev-bundle-index-image-version)
        OPERATOR_VERSION=$(awk '/^VERSION \?=/ {print $3}' Makefile)
        REPO=localhost:5000
        IMG=${REPO}/gatekeeper-operator:${GITHUB_SHA}
        PREV_BUNDLE_INDEX_IMG=quay.io/gatekeeper/gatekeeper-operator-bundle-index:${PREV_BUNDLE_INDEX_IMG_VERSION}
        make build-and-push-bundle-images IMG=${IMG} REPO=${REPO} VERSION=${GITHUB_SHA} OPERATOR_VERSION=${OPERATOR_VERSION} PREV_BUNDLE_INDEX_IMG=${PREV_BUNDLE_INDEX_IMG}

    - name: Deploy OLM
      run: |
        make deploy-olm

    - name: Deploy resources on KIND cluster to install Gatekeeper
      run: |
        make deploy-using-olm REPO=localhost:5000 VERSION=$GITHUB_SHA NAMESPACE=mygatekeeper

    - name: E2E Tests
      run: |
        make test-e2e NAMESPACE=mygatekeeper
        kubectl delete --wait namespace mygatekeeper
