name: Build and Push Docker Image
run-name: ${{ gitea.actor }} is building and pushing a Docker Image

on:
  push:
    branches:
      - master
      - staging
      - dev
  pull_request:
    branches:
      - master
      - staging
      - dev

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Install bump2version
        run: pip install bump2version

      - name: Get current version from bump2version
        id: version
        run: echo "VERSION=$(bump2version --dry-run --list patch | grep current_version | sed -r s,"^.*=",,)" >> $GITHUB_ENV

      - name: Set Docker tag based on branch
        id: tag
        run: |
          # master branch uses specific version tagging, others use the branch name
          if [[ "${{ gitea.ref_name }}" == "master" ]]; then
            TAG="${{ env.VERSION }}"
          else
            TAG="${{ gitea.ref_name }}"
          fi
          echo "TAG=$TAG" >> $GITHUB_ENV

      - name: Build Docker image
        run: |
          docker build -t pyrss-website:${{ env.TAG }} .

      - name: Login to Docker registry
        run: echo ${{ secrets.DOCKER_TOKEN }} | docker login -u ${{ secrets.DOCKER_USERNAME }} --password-stdin

      - name: Tag & Push Docker image
        run: |
          # Push the branch-specific or version-specific tag
          docker tag pyrss-website:${{ env.TAG }} xordk/pyrss-website:${{ env.TAG }}
          docker push xordk/pyrss-website:${{ env.TAG }}

          # If on master, push an additional "latest" tag
          if [[ "${{ gitea.ref_name }}" == "master" ]]; then
            docker tag pyrss-website:${{ env.TAG }} xordk/pyrss-website:latest
            docker push xordk/pyrss-website:latest
          fi
