name: Tests

on: [push]

env:
  CARGO_TERM_COLOR: always

jobs:
  build:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres
        env:
          POSTGRES_USER: postgres_user
          POSTGRES_PASSWORD: test
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
        ports:
          - 5432:5432
    steps:
    - uses: actions/checkout@v6

    - name: Clean up old caches
      run: |
        # Delete caches older than 7 days to prevent storage bloat
        gh cache list --limit 100 --json id,key,createdAt | \
        jq -r '.[] | select(.createdAt < (now - 7*24*60*60 | strftime("%Y-%m-%dT%H:%M:%SZ"))) | .id' | \
        xargs -I{} gh cache delete {} || true
      env:
        GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      continue-on-error: true

    - name: Set up Rust cache
      uses: Swatinem/rust-cache@v2
      with:
        # GitHub automatically evicts caches after 7 days of inactivity
        # rust-cache also cleans build artifacts older than 1 week
        shared-key: "ayb-tests"

    - name: Build
      run: cargo build --verbose

    - name: Ensure fmt finds no changes
      run: cargo fmt --check

    - name: Ensure clippy finds no issues
      run: cargo clippy -- -D warnings

    - name: Install nsjail requirements
      run: sudo apt-get install -y libprotobuf-dev protobuf-compiler libnl-route-3-dev

    - name: Cache Python environment
      uses: actions/cache@v4
      with:
        path: tests/test-env
        key: ${{ runner.os }}-pip-${{ hashFiles('tests/set_up_e2e_env.sh') }}

    - name: Cache nsjail binary
      id: cache-nsjail
      uses: actions/cache@v4
      with:
        path: tests/nsjail
        key: ${{ runner.os }}-nsjail-${{ hashFiles('scripts/build_nsjail.sh') }}

    - name: Set up environment for end-to-end tests
      run: tests/set_up_e2e_env.sh

    - name: Run tests
      run: cargo test --verbose
      env:
        RUST_BACKTRACE: 1

    - name: Upload screenshots on failure
      if: failure()
      uses: actions/upload-artifact@v5
      with:
        name: test-screenshots-${{ github.run_id }}
        path: tests/screenshots/
        retention-days: 7
