name: Build sources
on:
  push:
    branches:
    - main
    paths:
    - 'src/**'
    - '.github/workflows/build.yaml'

concurrency:
  group: ${{ github.workflow }}
  cancel-in-progress: true

jobs:
  build:
    env:
      RUSTC_WRAPPER: sccache
      SCCACHE_CACHE_SIZE: 2G
      SCCACHE_VERSION: 0.3.0
    runs-on: ubuntu-latest
    steps:
    -
      uses: actions/checkout@v4
    -
      uses: google/wireit@setup-github-actions-caching/v1
    -
      name: Cache rust stuff
      uses: actions/cache@v4
      with:
        path: |
         ~/.cargo/registry/index
         ~/.cargo/registry/cache
         ~/.cargo/git/db
         ~/.cargo/bin
         src/rust/**/target/
        key: ${{ runner.os }}-cargo3-${{ hashFiles('**/Cargo.lock') }}
        restore-keys: |
          ${{ runner.os }}-cargo3-
    -
      name: sccache
      uses: actions/cache@v4
      with:
        path: ~/.cache/sccache
        key: ${{ runner.os }}-sccache-${{ github.sha }}
        restore-keys: ${{ runner.os }}-sccache-
    -
      uses: actions-rs/toolchain@v1
      with:
        toolchain: nightly
        override: true
        target: wasm32-unknown-unknown
    -
      name: Install build dependencies
      env:
        GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      run: |
        sudo ln -s $(which wasm-ld-13 || which wasm-ld-12 || which wasm-ld-11 || which wasm-ld-10) /usr/bin/wasm-ld
        
        AIDOKU_CLI_VER=$(gh api repos/Aidoku/aidoku-cli/releases -q '.[0].tag_name')
        gh release download -R Aidoku/aidoku-cli "$AIDOKU_CLI_VER" -p *_amd64.deb
        sudo dpkg -i "aidoku-cli_${AIDOKU_CLI_VER:1}_linux_amd64.deb"

        SCCACHE_FILE=sccache-v$SCCACHE_VERSION-x86_64-unknown-linux-musl
        curl -L https://github.com/mozilla/sccache/releases/download/v$SCCACHE_VERSION/$SCCACHE_FILE.tar.gz | tar -xz
        sudo mv -f $SCCACHE_FILE/sccache /usr/local/bin/sccache
        sudo chmod +x /usr/local/bin/sccache
    -
      name: Build Rust sources
      run: |
        for src in ./src/rust/*; do
          (
            cd "$src"
            ./build.sh -a
          )
        done
    -
      name: Building source list
      run: |
        aidoku build ./**/*.aix
    -
      name: Deploy to GitHub Pages
      uses: JamesIves/github-pages-deploy-action@v4.7.2
      if: ${{ github.ref == 'refs/heads/main' }}
      with:
        branch: gh-pages
        folder: public
        git-config-name: GitHub Actions
        git-config-email: github-actions[bot]@users.noreply.github.com
        commit-message: Update source list
        single-commit: true
    - 
      name: Uploading packages as artifact
      uses: actions/upload-artifact@v4
      if: always()
      with:
        name: packages
        path: public/sources/*.aix
        if-no-files-found: ignore
    -
      name: Uploading gh-pages deployment as artifact
      uses: actions/upload-artifact@v4
      if: always()
      with:
        name: gh-pages
        path: public
        if-no-files-found: ignore

