name: Deploy

on:
  workflow_dispatch:
    
jobs:
  deploy:
    name: Deploy
    runs-on: ubuntu-latest
    timeout-minutes: 5
    environment: "Prod Grossebeuteu"

    env:
      GITHUB_REF: ${{ github.ref }}
      DOCKER_REGISTRY: ghcr.io
      DOCKER_IMAGE: polynux/pchl

    steps:
      - uses: actions/checkout@v2

      - name: Creating envs
        run: |
          echo "IMAGE_TAG=sha-$(git rev-parse --short HEAD)" >> $GITHUB_ENV
          echo "DOCKER_IMAGE_URI=${{ env.DOCKER_REGISTRY }}/${{ env.DOCKER_IMAGE }}" >> $GITHUB_ENV

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v1
        with:
          registry: ${{ env.DOCKER_REGISTRY }}
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build docker image and push
        uses: docker/build-push-action@v2
        with:
          context: .
          push: true
          tags: ${{ env.DOCKER_IMAGE_URI }}:${{ env.IMAGE_TAG }},${{ env.DOCKER_IMAGE_URI }}:latest

      - name: Sleep for 10 seconds
        run: sleep 10s
        shell: bash

      - name: Deploy stack to Portainer
        uses: carlrygart/portainer-stack-deploy@v1.3.0
        with:
          portainer-host: ${{ secrets.PORTAINER_HOST }}
          username: ${{ secrets.PORTAINER_USERNAME }}
          password: ${{ secrets.PORTAINER_PASSWORD }}
          stack-name: 'pchl'
          stack-definition: 'stack-definition.yml'
          template-variables: '{"PB_API": "${{ secrets.PB_API }}"}'
          image: ${{ env.DOCKER_IMAGE_URI }}:${{ env.IMAGE_TAG }}
