# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time
# For more information see: https://docs.github.com/en/actions/use-cases-and-examples/building-and-testing/building-and-testing-java-with-maven

name: Java CI with Maven

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

jobs:
  build:

    runs-on: ubuntu-latest
    #container:
    #  image: ghcr.io/catthehacker/ubuntu:act-latest # the large image
    strategy:
      matrix:
        java: [ '17' ]

    steps:
      - uses: actions/checkout@v4
      - name: Set up JDK {% raw %}${{matrix.java}}{% endraw %}
        uses: https://github.com/actions/setup-java@v4
        with:
          java-version: '{% raw %}${{matrix.java}}{% endraw %}'
          distribution: 'adopt'
          cache: maven
      - name: Build with Maven Wrapper
        run: ./mvnw -B -DskipTests verify
      - name: Build image
        #run: ./mvnw spring-boot:build-image # the original image build
        run: |
          export CONTAINER_REPO=$(echo {% raw %}${{ env.GITHUB_REPOSITORY }}{% endraw %} | tr '[:upper:]' '[:lower:]')
          ./mvnw com.google.cloud.tools:jib-maven-plugin:3.4.4:build -Djib.allowInsecureRegistries=true -Dimage=gitea./${CONTAINER_REPO}:latest -Djib.to.auth.username={% raw %}${{ secrets.PACKAGES_USER }}{% endraw %} -Djib.to.auth.password={% raw %}${{ secrets.PACKAGES_TOKEN }}{% endraw %} -Djib.from.platforms=linux/arm64,linux/amd64
      - name: Build image as tar
        run: |
          ./mvnw com.google.cloud.tools:jib-maven-plugin:3.4.4:buildTar -Djib.allowInsecureRegistries=true
      # separating the trivy scan into another job is not necessary. It, however, demonstrates forgejo's compatibility with GitHub
      - uses: forgejo/upload-artifact@v4
        with:
          name: petclinic-image
          path: target/jib-image.tar
        env:
          NODE_TLS_REJECT_UNAUTHORIZED: 0 # This is necessary due to self signed certs for forgejo, proper setups can skip this

  securityscan:
    runs-on: ubuntu-latest
    #container:
     # image: aquasec/trivy # the container does not contain node...
    steps:
      - uses: forgejo/download-artifact@v4
        with:
          name: petclinic-image
        env:
          NODE_TLS_REJECT_UNAUTHORIZED: 0 # This is necessary due to self signed certs for forgejo, proper setups can skip this
      - name: install trivy from deb package
        run: |
          if [[ "$(uname -m)" == "x86_64" ]]; then
            wget -O trivy.deb https://github.com/aquasecurity/trivy/releases/download/v0.58.0/trivy_0.58.0_Linux-64bit.deb
          else
            wget -O trivy.deb https://github.com/aquasecurity/trivy/releases/download/v0.58.0/trivy_0.58.0_Linux-ARM64.deb
          fi
          DEBIAN_FRONTEND=noninteractive dpkg -i trivy.deb
      - name: scan the image
        run: trivy image --input jib-image.tar
