name: Release

on:
  push:
    branches:
      - master

jobs:
  release:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:14.5
        env:
          POSTGRES_PASSWORD: postgres
          POSTGRES_USER: postgres
          POSTGRES_DB: postgres
        ports:
          - 5432:5432
        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5

    steps:
      - uses: actions/checkout@v3
      
      # Setup .npmrc file to publish to npm
      - uses: actions/setup-node@v3
        with:
          node-version: '18.x'
          registry-url: 'https://registry.npmjs.org'
      
      # Set up PostgreSQL client
      - run: sudo apt-get -yqq install postgresql-client
      - run: npm i -g db-migrate@0.11.13 db-migrate-pg@1.3.2

      # waiting https://github.com/ds300/patch-package/issues/339
      - run: npm install 2>&1 || true && npm run test:init 2>&1 || true && npm run test:updb && npm run test:release

      # resolve version
      - run: set -x; PACKAGE=$(cat package.json | jq -r '.["name"]')  VERNPM=$(curl https://registry.npmjs.org/$PACKAGE | jq -r '.["dist-tags"].latest' | awk -F. -v OFS=. '{$NF += 1 ; print}')   VERLOC=$(cat package.json | jq -r '.["version"]')   VEROUT=$(printf "$VERNPM\n$VERLOC\n" | sort -V -r | awk 'NR==1 {print; exit}') &&  jq -r '.version = "'${VEROUT}'"' package.json > /tmp/package.json && mv /tmp/package.json ./package.json

      - run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
