name: CI

on:
  push:
    branches: [ "main" ]
    paths-ignore: [ "terraform/**" ]
  pull_request:
    branches: [ "main" ]
    paths-ignore: [ "terraform/**" ]

env:
  REGISTRY: rg.fr-par.scw.cloud/knot-dots

jobs:

  test:

    timeout-minutes: 60

    runs-on: ubuntu-latest

    container:
      image: mcr.microsoft.com/playwright:v1.32.0-focal

    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 18
      - run: npm ci
      - run: npx playwright test
      - uses: actions/upload-artifact@v3
        if: failure()
        with:
          name: test-results
          path: test-results/
          retention-days: 7

  build:

    needs: [ test ]

    runs-on: ubuntu-latest

    steps:
      - uses: docker/login-action@v2
        with:
          registry: ${{ env.REGISTRY }}
          username: nologin
          password: ${{ secrets.SCW_SECRET_KEY }}
      - uses: docker/build-push-action@v4
        with:
          cache-from: type=registry,ref=${{ env.REGISTRY }}/strategytool:latest
          cache-to: type=inline
          file: docker/app/Dockerfile
          target: production
          push: ${{ github.event_name == 'push' }}
          tags: |
            ${{ env.REGISTRY }}/strategytool:${{ github.sha }}
            ${{ env.REGISTRY }}/strategytool:latest

  update:

    if: github.event_name == 'push'

    needs: [ build ]

    runs-on: ubuntu-latest

    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v3
      - run: |
          echo 'strategytool_image = "${{ env.REGISTRY }}/strategytool:${{ github.sha }}"' > ./terraform/dev/terraform.tfvars
          git config --global user.name github-actions
          git config --global user.email github-actions@github.com
          git commit -am "Update image tag"
          git push
