name: CI check on every PR
on:
  pull_request:
    branches:
      - master
    paths-ignore:
      - '**.md'
      - 'Makefile'
      - 'config.json'

jobs:
  ci:
    name: CI check on every push and PR
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Install Go
        uses: actions/setup-go@v3
        with:
          go-version: '1.22'

      - name: Setup necessary packages
        run: |
          sudo apt update && sudo apt install libvips-dev -y

      - name: run test cases
        run: make && make test
        
  image-test:
    name: Check for image build and CVE
    runs-on: ubuntu-latest
    permissions: 
      pull-requests: write 
    steps:
      - name: Checkout
        uses: actions/checkout@v3
        with:
          submodules: true

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

      - name: Cache Docker layers
        uses: actions/cache@v2
        with:
          path: /tmp/.buildx-cache
          key: ${{ runner.os }}-buildx-${{ github.sha }}
          restore-keys: |
            ${{ runner.os }}-buildx-

      - name: Build and load image
        uses: docker/build-push-action@v3
        with:
          context: .
          load: true
          tags: |
            ghcr.io/${{ github.event.repository.full_name }}:latest

          cache-from: type=local,src=/tmp/.buildx-cache
          cache-to: type=local,dest=/tmp/.buildx-cache-new,mode=max

      - name: Install trivy
        run: |
          wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | sudo apt-key add -
          echo deb https://aquasecurity.github.io/trivy-repo/deb $(lsb_release -sc) main | sudo tee -a /etc/apt/sources.list.d/trivy.list
          sudo apt-get update
          sudo apt-get install trivy -y
      
      - name: Scan for CVE
        uses: mathiasvr/command-output@v1
        id: trivy
        with:
          run: |
            trivy image --no-progress --severity "HIGH,CRITICAL" --ignore-unfixed ghcr.io/${{ github.event.repository.full_name }}
      
      - name: Print CVE
        run: |
          echo "${{ steps.trivy.outputs.stdout }}"

      - name: Comment PR for CVE
        uses: thollander/actions-comment-pull-request@v2
        with:
          message: |
            ```
            ${{ steps.trivy.outputs.stdout }}
            ```
          comment_tag: cve
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
