name: Publish Docker Image

concurrency:
  group: docker-${{ github.event_name }}-${{ github.ref }}
  cancel-in-progress: true

on:
  push:
    branches:
      - 'main'
    tags:
      - '*'

jobs:
  docker:
    name: Docker
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Set up QEMU
        uses: docker/setup-qemu-action@v3
        with:
          platforms: all

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

      - name: Login to DockerHub
        uses: docker/login-action@v3
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      - name: Login to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.repository_owner }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Get Version
        id: shell
        run: |
          echo "version=$(git describe --tags --abbrev=0)" >> $GITHUB_OUTPUT

      - name: Build and Push (dev)
        if: github.ref == 'refs/heads/main'
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
          tags: |
            xjasonlyu/tun2socks:dev
            ghcr.io/xjasonlyu/tun2socks:dev
          cache-from: type=gha
          cache-to: type=gha,mode=max

      - name: Build and Push (latest)
        if: startsWith(github.ref, 'refs/tags/')
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          platforms: linux/amd64,linux/arm/v6,linux/arm/v7,linux/arm64
          tags: |
            xjasonlyu/tun2socks:latest
            xjasonlyu/tun2socks:${{ steps.shell.outputs.version }}
            ghcr.io/xjasonlyu/tun2socks:latest
            ghcr.io/xjasonlyu/tun2socks:${{ steps.shell.outputs.version }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
