name: CI

on:
  push:
    branches: [ main ]
    paths-ignore:
      - 'doc/**'
      - 'README.md'
      - '.readthedocs.yaml'
  pull_request:
    branches: [ main ]
    paths-ignore:
      - 'doc/**'
      - 'README.md'
      - '.readthedocs.yaml'
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-20.04

    steps:
      - uses: actions/checkout@v3

      - name: Cache toolchain
        uses: actions/cache@v3
        env:
          cache-name: cache-toolchain
        with:
          path: |
            /opt/gcc-arm-9.2-2019.12-x86_64-arm-none-linux-gnueabihf
          key: ${{ runner.os }}-build-${{ env.cache-name }}
          restore-keys: |
            ${{ runner.os }}-build-
            ${{ runner.os }}-

      - name: Install prerequisites
        run: |
          sudo apt update
          sudo apt install -y curl make qemu-system-arm
          curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > rustup-init.sh
          chmod +x rustup-init.sh
          ./rustup-init.sh -y
          rustup install stable
          rustup target add armv7-unknown-linux-gnueabihf
          rm ./rustup-init.sh
          ln -s /usr/bin/qemu-system-arm /usr/local/bin/qemu-system-arm

      - name: Download and extract prebuilt toolchain
        run: |
          if [ ! -d "/opt/gcc-arm-9.2-2019.12-x86_64-arm-none-linux-gnueabihf" ]; then
          wget https://armkeil.blob.core.windows.net/developer/Files/downloads/gnu-a/9.2-2019.12/binrel/gcc-arm-9.2-2019.12-x86_64-arm-none-linux-gnueabihf.tar.xz
          tar -xvf gcc-arm-9.2-2019.12-x86_64-arm-none-linux-gnueabihf.tar.xz
          mv gcc-arm-9.2-2019.12-x86_64-arm-none-linux-gnueabihf /opt/gcc-arm-9.2-2019.12-x86_64-arm-none-linux-gnueabihf
          rm -f *.tar.xz
          /opt/gcc-arm-9.2-2019.12-x86_64-arm-none-linux-gnueabihf/bin/arm-none-linux-gnueabihf-gcc --version
          fi

      - name: Build all
        run: |
          make

      - name: Upload build asserts
        uses: actions/upload-artifact@v3.1.2
        with:
          name: v2p_ca9.elf
          path: |
            ./build/v2p_ca9.elf

      - name: Run tests
        run: |
          timeout --foreground -s SIGKILL 2m make qemu || {
            exit 0
          }