name: CI
on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main
jobs:
  run-unit-tests:
    name: Run unit tests
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    - uses: actions/setup-node@v4
      with:
        node-version: '20'
    - name: Install npm packages
      run: |
        npm install -g npm@latest
        npm ci
        npm ls --production --depth=0
    - name: Run style check
      run: npm run stylecheck
    - name: Run unit tests
      run: npm run test
  run-e2e-tests:
    name: Run e2e tests
    runs-on: ubuntu-latest
    needs: [ run-unit-tests ]
    strategy:
      matrix:
        include:
          - COUCHDB_IMAGE: couchdb:3
            NIGHTWATCH_SKIPTAGS: "search,nonpartitioned,couchdb-v2-only"
          - COUCHDB_IMAGE: couchdb:2.3.1
            NIGHTWATCH_SKIPTAGS: "search,partitioned"
    steps:
    - uses: actions/checkout@v4
    - uses: actions/setup-node@v4
      with:
        node-version: '20'
        cache: 'npm'
    - run: ./bin/build-couchdb-dev.sh
      env:
        COUCHDB_IMAGE: ${{ matrix.COUCHDB_IMAGE }}
        NIGHTWATCH_SKIPTAGS: ${{ matrix.NIGHTWATCH_SKIPTAGS }}
    - name: Install npm packages
      run: |
        npm install -g npm@latest
        npm ci
        npm ls --production --depth=0
    - name: Set up chromedriver
      run: ./bin/install-npm-chromedriver.sh
    - name: Start CouchDB
      env:
        COUCHDB_IMAGE: ${{ matrix.COUCHDB_IMAGE }}
        NIGHTWATCH_SKIPTAGS: ${{ matrix.NIGHTWATCH_SKIPTAGS }}
      run: |
        ./bin/docker-up-and-check.sh
        curl http://127.0.0.1:5984
    - name: Configure display
      run: |
        export DISPLAY=:99
        sudo apt-get install xvfb
    - name: Start Fauxton
      env:
        COUCHDB_IMAGE: ${{ matrix.COUCHDB_IMAGE }}
        NIGHTWATCH_SKIPTAGS: ${{ matrix.NIGHTWATCH_SKIPTAGS }}
      run: |
        grunt debugDev
        DIST=./dist/debug ./bin/fauxton &
        sleep 10
        curl http://localhost:8000
    - name: Run e2e tests
      env:
        COUCHDB_IMAGE: ${{ matrix.COUCHDB_IMAGE }}
        NIGHTWATCH_SKIPTAGS: ${{ matrix.NIGHTWATCH_SKIPTAGS }}
      run: xvfb-run --auto-servernum ./node_modules/.bin/grunt nightwatch_retries
    - name: Shutdown CouchDB
      env:
        COUCHDB_IMAGE: ${{ matrix.COUCHDB_IMAGE }}
      run: npm run docker:down
