name: Build and publish Docker image

on:
  push:
  pull_request:
  workflow_dispatch:

env:
  REGISTRY: git.newpipe-ev.de
  # make sure the name is lowercase, otherwise Docker won't accept it
  IMAGE_NAME: newpipe-ev/website

jobs:
  build:
    runs-on: ubuntu-latest

    permissions:
      contents: read

    steps:
      - uses: actions/checkout@v4

      - name: Generate suitable tag for kaniko
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

      - name: Extract tag for kaniko action
        id: tag
        env:
          TAG: ${{ steps.meta.outputs.tags }}
        run: |
          echo "TAG=$TAG"
          echo "::set-output name=tag::${TAG##*:}"

      - name: Build Docker image with kaniko
        uses: https://code.thetadev.de/ThetaDev/action-kaniko@dbb8da86cf2d498dde8ec1b3be967ceda17a21ff
        with:
          image: ${{ env.IMAGE_NAME }}
          registry: ${{ env.REGISTRY }}
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}
          tag: ${{ steps.tag.outputs.tag }}
          platforms: linux/amd64
          tag_with_latest: ${{ gitea.ref == format('refs/heads/{0}', gitea.event.repository.default_branch) }}

      - name: Trigger redeployment
        if: gitea.ref == format('refs/heads/{0}', gitea.event.repository.default_branch)
        env:
          UPDATE_URL: ${{ secrets.UPDATE_URL }}
          UPDATE_TOKEN: ${{ secrets.UPDATE_TOKEN }}
        run: |
          curl --fail-with-body "$UPDATE_URL" -H "Authorization: Bearer ${UPDATE_TOKEN}"
