name: Build and push Docker image

on:
  push:
  pull_request:
  schedule:
    - cron: '0 2 * * 0'
  workflow_dispatch:

env:
  CI: true
  DOCKER_BUILDKIT: 1

jobs:
  main:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        CPU_ARCH:
          - aarch64
          - arm
          - i686
          - x86_64
    steps:

    - name: Clone repository
      uses: actions/checkout@v2

    - name: Setup binfmt_misc
      if: (matrix.CPU_ARCH == 'aarch64') || (matrix.CPU_ARCH == 'arm')
      run: docker run --rm --privileged aptman/qus -s -- -p aarch64 arm

    - name: Build images
      run: |
        case '${{ matrix.CPU_ARCH }}' in
          arm|aarch64) SYSTEM_TYPE=arm;;
          *) SYSTEM_TYPE=x86;;
        esac
        docker build -t \
          termux/termux-docker:${{ matrix.CPU_ARCH }} \
          --build-arg BOOTSTRAP_ARCH=${{ matrix.CPU_ARCH }} \
          --build-arg SYSTEM_TYPE="${SYSTEM_TYPE}" \
          .

    - name: Login to Docker Hub
      if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request' && github.repository == 'termux/termux-docker'
      uses: docker/login-action@v1
      with:
        username: grimler
        password: ${{ secrets.GRIMLER_DOCKER_TOKEN }}

    - name: Push to Docker Hub
      if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request' && github.repository == 'termux/termux-docker'
      run: |
        docker push termux/termux-docker:${{ matrix.CPU_ARCH }}
        if [ ${{ matrix.CPU_ARCH }} = i686 ]; then
          docker tag termux/termux-docker:i686 termux/termux-docker:latest
          docker push termux/termux-docker:latest
        fi
