name: "Release : NPM packages"

on:
  # Triggered manually
  workflow_dispatch:
    inputs:
      tag:
        description: "Tag"
        required: true
      targetEnv:
        description: "Target Environment"
        required: true
        type: choice
        options:
          - DEV
          - PROD
  # Triggered by release-nocodb.yml / release-nightly-dev.yml
  workflow_call:
    inputs:
      tag:
        description: "Tag"
        required: true
        type: string
      targetEnv:
        description: "Target Environment"
        required: true
        type: string
    secrets:
      NPM_TOKEN:
        required: true
#       GITHUB_TOKEN:
#         required: true
jobs:
  release:
    runs-on: ubuntu-latest
    env:
      working-directory: ./packages/nocodb
    strategy:
      matrix:
        node-version: [12]
    steps:
      - uses: actions/checkout@v2
      # Setup .npmrc file to publish to npm
      - uses: actions/setup-node@v2
        with:
          node-version: '16.x'
          registry-url: 'https://registry.npmjs.org'
      - run: |
          cd packages/nc-gui
          npm install
          targetEnv=${{ github.event.inputs.targetEnv || inputs.targetEnv }} targetVersion=${{ github.event.inputs.tag || inputs.tag }} npm run build:copy:jsdeliver
          cd ../..
          npm install
          targetEnv=${{ github.event.inputs.targetEnv || inputs.targetEnv }} targetVersion=${{ github.event.inputs.tag || inputs.tag }} node scripts/upgradeNcGui.js && cd packages/nocodb && npm run obfuscate:build:publish
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
      - name: Create Pull Request
        if: ${{ github.event.inputs.targetEnv == 'PROD' || inputs.targetEnv == 'PROD' }}
        id: cpr
        uses: peter-evans/create-pull-request@v3
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          #          commit-message: Update report
          #          committer: GitHub <noreply@github.com>
          #          author: ${{ github.actor }} <${{ github.actor }}@users.noreply.github.com>
          signoff: true
          branch: 'release/${{ github.event.inputs.tag || inputs.tag }}'
          delete-branch: true
          title: 'Release ${{ github.event.inputs.tag || inputs.tag }}'
          labels: |
            Bot: Automated PR
      - name: Check outputs
        if: ${{ github.event.inputs.targetEnv == 'PROD' || inputs.targetEnv == 'PROD' }}
        run: |
          echo "Pull Request Number - ${{ steps.cpr.outputs.pull-request-number }}"
          echo "Pull Request URL - ${{ steps.cpr.outputs.pull-request-url }}"
      - name: automerge
        uses: "pascalgn/automerge-action@v0.14.3"
        env:
          GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
          PULL_REQUEST: "${{ steps.cpr.outputs.pull-request-number }}"
