name: Docker Build

"on":
  workflow_dispatch:
  # Uncomment if you also want auto-builds on pushes:
  # push:
  #   branches: [ "main" ]

jobs:
  docker:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to Gitea Registry
        uses: docker/login-action@v3
        with:
          registry: gitea.cuihang1201.synology.me
          username: ${{ secrets.REGISTRY_USER }}
          password: ${{ secrets.REGISTRY_TOKEN }}

      - name: Build and push image
        uses: docker/build-push-action@v5
        with:
          context: .
          file: ./Dockerfile
          push: true
          tags: gitea.cuihang1201.synology.me/hangpersonal/docker-build:latest
    
      # Optional quick health check, runs detached and then cleaned up
      - name: Smoke test
        run: |
          docker run --name docker-build \
            gitea.cuihang1201.synology.me/hangpersonal/docker-build:latest
          sleep 5
        if: ${{ always() }}

      - name: Cleanup local container/images
        if: always()
        run: |
          echo "Stop container: "
          docker stop docker-build
          echo "Remove container: "
          docker rm -f docker-build 2>/dev/null || true
          echo "Remove image: "
          docker rmi gitea.cuihang1201.synology.me/hangpersonal/docker-build:latest
          docker image ls -a
