name: Build Ubuntu Bases
on: workflow_dispatch

jobs:
  build:
    runs-on: ubuntu-latest
    permissions:
      packages: write
    strategy:
      fail-fast: false
      matrix:
                    # tag           dockerfile in docker/     platforms
        dockerfile: [[ubuntu-18.04, Dockerfile.ubuntu-18.04, 'linux/amd64'],
                     [ubuntu-20.04, Dockerfile.ubuntu-20.04, 'linux/amd64']]

    name: Build ${{ matrix.dockerfile[0] }}
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - uses: actions/setup-go@v2
      - uses: imjasonh/setup-crane@01d26682810dcd47bfc8eb1efe791558123a9373
      - name: Display GitHub Action architecture
        run: lscpu
      - name: Set Container Tag
        run: |
          container="spliced-${{ matrix.dockerfile[0] }}:latest"
          echo "container=${container}" >> $GITHUB_ENV

      - name: Check ${{ matrix.dockerfile[1] }} Exists
        run: |
          printf "Preparing to build ${{ env.container }} from ${{ matrix.dockerfile[1] }}"
          if [ ! -f "docker/${{ matrix.dockerfile[1]}}" ]; then
              printf "Dockerfile ${{ matrix.dockerfile[0]}} does not exist"
              exit 1;
          fi

      - name: Pull Docker Layers
        run: docker pull ghcr.io/buildsi/${{ env.container }} || exit 0 

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v1

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

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v1
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build ${{ matrix.dockerfile[1] }}
        uses: docker/build-push-action@v2
        with:
          file: docker/${{matrix.dockerfile[1]}}
          platforms: ${{ matrix.dockerfile[2] }}
          context: .
          push: ${{ github.event_name != 'pull_request' }}
          tags: ghcr.io/buildsi/${{ env.container }}

      - name: Label
        if: ${{ github.event_name != 'pull_request' }}
        run: |
          docker run -i --rm ghcr.io/buildsi/${{ env.container }} spack compiler list --flat > compilers.txt
          labels=$(echo $(tr '\r\n' '|' < compilers.txt))
          labels="org.spack.compilers=${labels}"
          printf "Saving compiler labels ${labels}\n"         
          crane mutate ghcr.io/buildsi/${{ env.container }} --label "${labels}"
