name: Deploy

on:
  push:
    branches: [ 'development', 'master' ]
  pull_request:
    branches: [ 'development', 'master' ]

jobs:
  cancel-previous:
    name: 'Cancel Previous Runs'
    runs-on: ubuntu-latest
    timeout-minutes: 3
    steps:
      - uses: styfle/cancel-workflow-action@0.8.0
        with:
          access_token: ${{ github.token }}

  deploy:
    runs-on: ubuntu-latest
    needs: cancel-previous
    steps:
      - uses: actions/checkout@v2
        with:
          fetch-depth: 0
      - uses: actions/setup-node@v2-beta
        with:
          node-version: '14.17.6'
          registry-url: https://registry.npmjs.org/

      - name: Configure Git
        run: |
          git config --global user.email ${{ secrets.GH_EMAIL }}
          git config --global user.name ${{ secrets.GH_USER }}
          git remote set-url origin "https://${{ github.token }}@github.com/energywebfoundation/ew-did-registry.git" > /dev/null 2>&1
          git reset --hard
          git fetch -u origin master:master
          git fetch -u origin development:development

      - name: Set npm credentials
        run: npm config set //registry.npmjs.org/:_authToken ${{ secrets.NPM_TOKEN }}

      - name: Install package
        run: |
          npm ci
          npm run setup

      - name: Build package
        run: npm run build

      - name: Npm run test
        run: npm run test-rpc

      - name: Output Run number
        run: echo ${{ github.run_number }}

      - name: Deploy on development branch
        if: github.ref == 'refs/heads/development'
        env:
          RUN_NUMBER: ${{ github.run_number }}
        run: |
          npm run publish:canary

      - name: Deploy on master branch
        if: github.ref == 'refs/heads/master'
        uses: codfish/semantic-release-action@v1
        env:
            GITHUB_TOKEN: ${{ secrets.GH_TOKEN_CI }}
            NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
        
      - name: Commit to develop branch and merge to master branch
        run: |
          git checkout development
          git merge origin/master
          git push origin development
