name: PKCS11 Tests

on: [push, pull_request]

jobs:
  init:
    name: Initializing Workflow
    runs-on: ubuntu-latest
    outputs:
      matrix: ${{ steps.init.outputs.matrix }}
      repo: ${{ steps.init.outputs.repo }}
    steps:
      - name: Clone repository
        uses: actions/checkout@v3

      - name: Initialize workflow
        id: init
        env:
          BASE64_MATRIX: ${{ secrets.BASE64_MATRIX }}
          BASE64_REPO: ${{ secrets.BASE64_REPO }}
        run: |
          tests/bin/init-workflow.sh

  build:
    name: Building JSS
    needs: init
    runs-on: ubuntu-latest
    strategy:
      matrix: ${{ fromJSON(needs.init.outputs.matrix) }}
    steps:
      - name: Clone repository
        uses: actions/checkout@v3

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v2

      - name: Build runner image
        uses: docker/build-push-action@v3
        with:
          context: .
          build-args: |
            BASE_IMAGE=registry.fedoraproject.org/fedora:${{ matrix.os }}
            COPR_REPO=${{ needs.init.outputs.repo }}
            BUILD_OPTS=--with-timestamp --with-commit-id
          tags: jss-runner
          target: jss-runner
          outputs: type=docker,dest=pkcs11-runner.tar

      - name: Store runner image
        uses: actions/cache@v3
        with:
          key: pkcs11-runner-${{ matrix.os }}-${{ github.run_id }}
          path: pkcs11-runner.tar

  pkcs11-constants-test:
    name: Testing PKCS11 Constants
    needs: [init, build]
    runs-on: ubuntu-latest
    env:
      SHARED: /tmp/workdir/jss
    strategy:
      matrix: ${{ fromJSON(needs.init.outputs.matrix) }}
    steps:
      - name: Clone repository
        uses: actions/checkout@v3

      - name: Retrieve runner image
        uses: actions/cache@v3
        with:
          key: pkcs11-runner-${{ matrix.os }}-${{ github.run_id }}
          path: pkcs11-runner.tar

      - name: Load runner image
        run: docker load --input pkcs11-runner.tar

      - name: Run container
        run: |
          IMAGE=jss-runner \
          NAME=jss \
          HOSTNAME=jss.example.com \
          tests/bin/runner-init.sh

      - name: Install dependencies
        run: docker exec jss dnf install -y nss-util-devel python3 java-devel

      - name: Generate PKCS11 constants
        run: |
          docker exec jss python3 $SHARED/tools/build_pkcs11_constants.py \
                   --pkcs11t /usr/include/nss3/pkcs11t.h \
                   --pkcs11n /usr/include/nss3/pkcs11n.h \
                   -o PKCS11Constants.java \
                   --verbose
          docker exec jss diff PKCS11Constants.java $SHARED/base/src/main/java/org/mozilla/jss/pkcs11/PKCS11Constants.java
