name: Docker
on:
  push:
    paths:
      - .github/workflows/docker.yml
      - Dockerfile
    branches-ignore:
      - master
  release:
    types:
      - published
jobs:
  ubuntu:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        version: ["16.04", "18.04", "20.04"]
    steps:
      - name: Checkout
        uses: actions/checkout@main
        with:
          fetch-depth: 0
          persist-credentials: false
      - name: Fetch origin/master from Git
        run: git fetch origin master

      - name: Build Docker image
        run: docker build -t brew --build-arg=version=${{matrix.version}} .

      - name: Run brew test-bot --only-setup
        run: docker run --rm brew brew test-bot --only-setup

      - name: Deploy the tagged Docker image to GitHub Packages
        if: startsWith(github.ref, 'refs/tags/')
        run: |
          brew_version=${GITHUB_REF:10}
          echo "brew_version=$brew_version" >> ${GITHUB_ENV}
          echo ${{secrets.HOMEBREW_GITHUB_PACKAGES_API_TOKEN}} | docker login ghcr.io -u BrewTestBot --password-stdin
          docker tag brew "ghcr.io/homebrew/ubuntu${{matrix.version}}:$brew_version"
          docker push "ghcr.io/homebrew/ubuntu${{matrix.version}}:$brew_version"
          docker tag brew "ghcr.io/homebrew/ubuntu${{matrix.version}}:latest"
          docker push "ghcr.io/homebrew/ubuntu${{matrix.version}}:latest"

      - name: Deploy the tagged Docker image to Docker Hub
        if: startsWith(github.ref, 'refs/tags/')
        run: |
          echo ${{secrets.DOCKER_TOKEN}} | docker login -u brewtestbot --password-stdin
          docker tag brew "homebrew/ubuntu${{matrix.version}}:$brew_version"
          docker push "homebrew/ubuntu${{matrix.version}}:$brew_version"
          docker tag brew "homebrew/ubuntu${{matrix.version}}:latest"
          docker push "homebrew/ubuntu${{matrix.version}}:latest"

      - name: Deploy the homebrew/brew Docker image to GitHub Packages and Docker Hub
        if: startsWith(github.ref, 'refs/tags/') && matrix.version == '20.04'
        run: |
          docker tag brew "ghcr.io/homebrew/brew:$brew_version"
          docker push "ghcr.io/homebrew/brew:$brew_version"
          docker tag brew "ghcr.io/homebrew/brew:latest"
          docker push "ghcr.io/homebrew/brew:latest"
          docker tag brew "homebrew/brew:$brew_version"
          docker push "homebrew/brew:$brew_version"
          docker tag brew "homebrew/brew:latest"
          docker push "homebrew/brew:latest"
