name: CI

on:
  push:
    branches:
      - '**'
      - "!.github/**"
      - "!README.md"
      
env:
  SERVICE_NAME: policy-service
jobs:

  annotations:
    runs-on: self-hosted-org-master
    steps:
      - name: Notice about branch
        run: |
          text="executed from branch: `echo ${GITHUB_REF#refs/heads/}`"
          echo "::notice::${text}"
          
  deploy-dev-X:
    runs-on: self-hosted-org-master
    if: github.ref == 'refs/heads/development' && github.event_name == 'push'
    needs: [test]
    steps:
      - name: deployment do DEV-X
        run: |
          for i in dev-1 dev-2 dev-3 dev-4;
          do
            echo "Trigger deployment for $i"
            curl -s \
            -X POST \
            -H "Accept: application/vnd.github.v3+json" \
            -H 'authorization: Bearer ${{ secrets.ORG_FULL_GITHUB_TOKEN }}' \
            https://api.github.com/repos/sky-distribution/policy-service/dispatches \
            -d '{"event_type":"dispatcher-trigger-digital-cicd", "client_payload": {"branch_name": "${{ github.head_ref }}", "target": "'$i'"}}'
            sleep 10;
          done
  test:
    runs-on: ubuntu-latest
    services:
      rabbitmq:
        image: rabbitmq:3.8
        ports:
          - 5672/tcp
        options: --health-cmd "rabbitmqctl node_health_check" --health-interval 10s --health-timeout 5s --health-retries 5

    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js
        uses: actions/setup-node@v3
        with:
          node-version-file: '.nvmrc'
          cache: 'npm'
      - name: Update to npm 8
        run: npm i -g npm@8.3

      - name: Install Dependencies
        run: npm ci --workspaces && cd app && npm ci && rm -f .npmrc
        env:
          NPM_TOKEN: ${{ secrets.ORG_NPM_READ_TOKEN }}

      - name: Lint
        run: npm run lint --workspaces

      - name: Build
        run: npm run app:build

      - name: Test
        run: npm run test --workspace=app
        env:
          RABBITMQ_URL: amqp://localhost:${{ job.services.rabbitmq.ports[5672] }}
          SERVICE_QUEUE_NAME: policy-service
          CMD_EXCHANGE_NAME: cmd-exchange

      - name: Static code analysis
        uses: SonarSource/sonarcloud-github-action@v1.6
        with:
          projectBaseDir: ./app
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          SONAR_TOKEN: ${{ secrets.ORG_SONAR_TOKEN }}
          # setting up proper encoding is required to handle filenames with polish / non ASCI chars
          LC_ALL: C.UTF-8
