name: publish-docker

on:
  push:
    paths-ignore:
      - "!.github/workflows/docker.yml"
      - ".github/**"
      - "docs/**"
      - "resources/**"
      - "benchmark/**"
      - "tests/**"
      - "**/*.md"
    branches:
      - main
    tags:
      - "v*.*.*"
  workflow_dispatch:
    inputs:
      repo_ref:
        required: true
        description: 'Set branch or tag or commit id. Default is ""'
        type: string
        default: ''
      image_tag:
        required: true
        description: 'Set docker image tag. Default is "latest"'
        type: string
        default: latest

jobs:
  publish_docker_image:
    runs-on: ubuntu-latest
    environment: 'prod'
    env:
      TAG_PREFIX: "openmmlab/lmdeploy"
      TAG: "openmmlab/lmdeploy:latest"
    steps:
      - name: Checkout repository
        uses: actions/checkout@v3
        with:
          ref: ${{github.event.inputs.repo_ref}}
      - name: Free disk space
        uses: jlumbroso/free-disk-space@main
        with:
          # This might remove tools that are actually needed, if set to "true" but frees about 6 GB
          tool-cache: false
          docker-images: false
          # All of these default to true, but feel free to set to "false" if necessary for your workflow
          android: true
          dotnet: true
          haskell: true
          large-packages: true
          swap-storage: false
      - name: Get docker info
        run: |
          docker info
          # remove http extraheader
          git config --local --unset "http.https://github.com/.extraheader"
      - name: Login to Docker Hub
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.DOCKERHUB_USERNAME }}
          password: ${{ secrets.DOCKERHUB_TOKEN }}
      - name: Update docker TAG from workflow input
        if: github.event_name == 'workflow_dispatch'
        run: |
          export TAG=$TAG_PREFIX:${{github.event.inputs.image_tag}}
          echo $TAG
          echo "TAG=${TAG}" >> $GITHUB_ENV
      - name: Build and push Docker image
        run: |
          echo $TAG
          docker build . -f docker/Dockerfile -t ${TAG} --no-cache
          docker push $TAG
      - name: Push docker image with released tag
        if: startsWith(github.ref, 'refs/tags/') == true
        run: |
          export RELEASE_TAG=${TAG_PREFIX}:${{github.ref_name}}
          echo $RELEASE_TAG
          docker tag $TAG $RELEASE_TAG
          docker push $RELEASE_TAG
