name: CI Kubernetes

on:
  push:
    branches: [ master, 'release/**' ]
    paths-ignore:
      - 'docs/**'
      - '**/*.md'
  pull_request:
    branches: [ master, 'release/**' ]
    paths-ignore:
      - 'docs/**'
      - '**/*.md'

concurrency:
  group: ${{ github.workflow }}-${{ github.ref == 'refs/heads/master' && github.run_number || github.ref }}
  cancel-in-progress: true

permissions:
  contents: read

jobs:
  kubernetes-discovery:
    strategy:
      fail-fast: false
      matrix:
        platform:
          - ubuntu-20.04
        os_name:
          - linux_openresty

    runs-on: ${{ matrix.platform }}
    timeout-minutes: 15
    env:
      SERVER_NAME: ${{ matrix.os_name }}
      OPENRESTY_VERSION: default

    steps:
      - name: Check out code
        uses: actions/checkout@v4
        with:
          submodules: recursive

      - name: Setup kubernetes cluster
        run: |
          KUBERNETES_VERSION="v1.22.7"

          kind create cluster --name apisix-test --config ./t/kubernetes/configs/kind.yaml --image kindest/node:${KUBERNETES_VERSION}

          kubectl wait --for=condition=Ready nodes --all --timeout=180s

          kubectl apply -f ./t/kubernetes/configs/account.yaml

          kubectl apply -f ./t/kubernetes/configs/endpoint.yaml

          KUBERNETES_CLIENT_TOKEN_CONTENT=$(kubectl get secrets | grep apisix-test | awk '{system("kubectl get secret -o jsonpath={.data.token} "$1" | base64 --decode")}')

          KUBERNETES_CLIENT_TOKEN_DIR="/tmp/var/run/secrets/kubernetes.io/serviceaccount"

          KUBERNETES_CLIENT_TOKEN_FILE=${KUBERNETES_CLIENT_TOKEN_DIR}/token

          mkdir -p ${KUBERNETES_CLIENT_TOKEN_DIR}
          echo -n "$KUBERNETES_CLIENT_TOKEN_CONTENT" > ${KUBERNETES_CLIENT_TOKEN_FILE}

          echo 'KUBERNETES_SERVICE_HOST=127.0.0.1'
          echo 'KUBERNETES_SERVICE_PORT=6443'
          echo 'KUBERNETES_CLIENT_TOKEN='"${KUBERNETES_CLIENT_TOKEN_CONTENT}"
          echo 'KUBERNETES_CLIENT_TOKEN_FILE='${KUBERNETES_CLIENT_TOKEN_FILE}

          kubectl proxy -p 6445 &

      - name: Linux Install
        run: |
          sudo ./ci/${{ matrix.os_name }}_runner.sh before_install
          sudo --preserve-env=OPENRESTY_VERSION ./ci/${{ matrix.os_name }}_runner.sh do_install

      - name: Run test cases
        run: |
          ./ci/kubernetes-ci.sh run_case
