name: ci

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [16, 18, 20]
        target: [test, test-multi, test-remote, coverage]

    env:
      CI: true
      PGUSER: postgres

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Update APT
        run: sudo apt update

      - name: Install OS dependencies
        run: sudo apt install socat

      - name: Check PostgreSQL version
        run: |
          client_ver="$(psql --version | gawk '{printf("%d", $3)}')"
          sudo sed -i 's/peer/\0 map=mymap/' "/etc/postgresql/$client_ver/main/pg_hba.conf"
          echo "mymap $USER postgres" | sudo tee -a "/etc/postgresql/$client_ver/main/pg_ident.conf"
          sudo systemctl enable postgresql
          sudo systemctl start postgresql
          sudo systemctl status postgresql
          server_ver="$(psql -c 'select version();' | gawk '/PostgreSQL/{printf("%d", $2)}')"
          test "$server_ver" = "$client_ver"
          echo "pg version: $client_ver"

      - name: Use Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node-version }}

      - name: Setup SSH
        run: |
          ssh-keygen -t rsa -f ~/.ssh/id_rsa -N ''
          cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
          ssh-keyscan -t rsa localhost >> ~/.ssh/known_hosts
          echo "PGHOST=$PGHOST" >> ~/.ssh/environment
          echo "PGUSER=$PGUSER" >> ~/.ssh/environment
          echo "PGPASSWORD=$PGPASSWORD" >> ~/.ssh/environment
          echo "NODE_CONFIG=$NODE_CONFIG" >> ~/.ssh/environment
          cat ~/.ssh/environment
          chmod 600 ~/.ssh/*
          chmod 700 ~/.ssh
          chmod 755 ~/
          echo PermitUserEnvironment=yes | sudo tee -a /etc/ssh/sshd_config
          sudo systemctl restart ssh.service
          ssh localhost 'echo $PGHOST'

      - name: Check version
        run: |
          test "$(node --version | cut -d . -f 1)" = "v${{ matrix.node-version }}"
          echo "PATH=\"$(dirname "$(which node)"):\$PATH\"" > ~/.bashrc.new
          cat ~/.bashrc >> ~/.bashrc.new
          mv ~/.bashrc.new ~/.bashrc
          node_ver="$(ssh localhost node --version)"
          echo "Node $node_ver"
          test "$(echo "$node_ver" | cut -d . -f 1)" = "v${{ matrix.node-version }}"

      - name: Install packages
        run: npm install

      - name: Lint
        run: npm run lint

      - name: Create database
        run: psql -c 'create database "qlobber-pg";'

      - name: Apply migrations
        run: npm run migrate up

      - name: Run target
        run: npm run ${{ matrix.target }}

      - name: Coveralls
        if: matrix.target == 'coverage'
        uses: coverallsapp/github-action@v2
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
