name: Build and Push Docker Image

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main
  workflow_dispatch:

jobs:
  docker:
    runs-on: docker-host
    steps:
      - name: Check out repository
        uses: actions/checkout@v4

      - name: Log in to Docker Hub
        env:
          DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
          DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
        run:
          echo "$DOCKERHUB_TOKEN" | docker login --username "$DOCKERHUB_USERNAME" --password-stdin

      - name: Build image
        env:
          IMAGE_NAME: ${{ vars.DOCKERHUB_REPOSITORY }}
        run:
          SHORT_SHA="$(git rev-parse --short HEAD)"
          docker build \
            --tag "$IMAGE_NAME:latest" \
            --tag "$IMAGE_NAME:$SHORT_SHA" \
            .

      - name: Push image
        env:
          IMAGE_NAME: ${{ vars.DOCKERHUB_REPOSITORY }}
        run:
          SHORT_SHA="$(git rev-parse --short HEAD)"
          docker push "$IMAGE_NAME:latest"
          docker push "$IMAGE_NAME:$SHORT_SHA"
