name: Publish Docker Image

on:
  push:
    branches:
      - "master"
      - "development"
    paths-ignore: # Files in here will not trigger a build
      - "README.md"
      - "sharex.sxcu"
      - "LICENSE"
      - "docker-compose.yml"
      - "media/*"

jobs:
  docker:
    runs-on: ubuntu-20.04
    steps:
      - name: Get branch name
        id: branch-name
        uses: tj-actions/branch-names@v7

      - name: Checkout
        uses: actions/checkout@v3

      - name: Restore Docker Cache
        uses: actions/cache@v3
        id: docker-cache
        with:
          path: /usr/bin/docker
          key: ${{ runner.os }}-docker

      - name: Install Docker (if not cached)
        if: steps.docker-cache.outputs.cache-hit != 'true'
        run: |
          wget -q -O /tmp/docker.tgz https://download.docker.com/linux/static/stable/x86_64/docker-20.10.23.tgz \
          && tar --extract --file /tmp/docker.tgz --directory /usr/bin --strip-components 1 --no-same-owner docker/docker \
          && rm -rf /tmp/* &&
          echo "Done"

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

      - name: Login to Repo
        uses: docker/login-action@v2
        with:
          username: ${{ secrets.REPO_USERNAME }}
          password: ${{ secrets.REPO_TOKEN }}

      - name: Restore Docker Build Cache
        uses: actions/cache@v3
        id: build-cache
        with:
          path: /tmp/.buildx-cache
          key: ${{ runner.os }}-buildx

      - name: Build and Push (Latest)
        uses: docker/build-push-action@v4
        if: steps.branch-name.outputs.current_branch == 'master'
        with:
          push: true
          context: .
          tags: fascinated/simple-links:latest
          cache-from: type=local,src=/tmp/.buildx-cache
          cache-to: type=local,dest=/tmp/.buildx-cache

      - name: Build and Push (Other Branches)
        uses: docker/build-push-action@v4
        if: steps.branch-name.outputs.current_branch != 'master'
        with:
          push: true
          context: .
          tags: fascinated/simple-links:${{ steps.branch-name.outputs.current_branch }}
          cache-from: type=local,src=/tmp/.buildx-cache
          cache-to: type=local,dest=/tmp/.buildx-cache

      - name: Save Docker Build Cache
        if: steps.build-cache.outputs.cache-hit != 'true'
        run: |
          mkdir -p /tmp/.buildx-cache
          cp -r /tmp/.buildx-cache/. /tmp/.buildx-cache-new
          rm -rf /tmp/.buildx-cache
          mv /tmp/.buildx-cache-new /tmp/.buildx-cache
