name: Build Docker Image
on:
  push:
    branches:
      - main
env:
  IMAGE_PATH: git.thuanle.me/public/ip-info

jobs:
  build:
    strategy:
      matrix:
        arch:
          - amd64
          - arm64
    runs-on: ${{ matrix.arch }}
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Fetch full history, keeping all commits

      - name: Get commit count
        id: get_commit_count
        run: |
          COMMIT_COUNT=$(git rev-list --count HEAD)
          echo "COMMIT_COUNT=${COMMIT_COUNT}" >> $GITHUB_ENV

      - name: Login to Docker Registry
        uses: docker/login-action@v3
        with:
          registry: git.thuanle.me
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Build Docker images
        run: |
          echo "Building image for architecture: ${{ matrix.arch }}"
          
          docker build \
            -f Dockerfile \
            -t ${{ env.IMAGE_PATH }}:${{ matrix.arch }}-latest \
            --label "version=${{ env.COMMIT_COUNT }}" \
            --label "build_date=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \
            --label "commit_sha=${{ github.sha }}" \
            .
          
          docker push ${{ env.IMAGE_PATH }}:${{ matrix.arch }}-latest          

  amend-manifest:
    runs-on: linux
    needs: [build]
    steps:
      - name: Login to Docker Registry
        uses: docker/login-action@v3
        with:
          registry: git.thuanle.me
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Push Docker manifest
        run: |
          echo "Delete existing manifest"
          docker manifest rm ${{ env.IMAGE_PATH }}:latest || true
          
          echo "Create new manifest"
          docker manifest create ${{ env.IMAGE_PATH }}:latest \
            ${{ env.IMAGE_PATH }}:amd64-latest \
            ${{ env.IMAGE_PATH }}:arm64-latest 
          
          docker manifest push ${{ env.IMAGE_PATH }}:latest