name: CI
on:
  push:
    branches:
      - master
  pull_request:
permissions:
  contents: read
env:
  HOMEBREW_BREW_GIT_REMOTE: https://github.com/Homebrew/brew
  HOMEBREW_CORE_GIT_REMOTE: https://github.com/Homebrew/homebrew-core
  HOMEBREW_CASK_GIT_REMOTE: https://github.com/Homebrew/homebrew-cask

jobs:
  tests:
    strategy:
      matrix:
        os:
          - macOS-latest
          - ubuntu-latest
        include:
          - os: macOS-latest
            shell: bash
          - os: ubuntu-latest
            shell: bash
    runs-on: ${{matrix.os}}
    defaults:
      run:
        shell: ${{ matrix.shell }}
    steps:
      - name: Set up Git repository
        uses: actions/checkout@main

      - name: Cleanup macOS
        if: runner.os == 'macOS'
        run: |
          sudo rm -rf /Applications/Xcode.app \
                      /Library/Developer/CommandLineTools
          sudo xcode-select --reset

      - name: Check Bash 3.x syntax
        if: runner.os == 'macOS'
        run: |
          /bin/bash -u -n install.sh
          /bin/bash -u -O extglob -n uninstall.sh

      - name: Set up Homebrew PATH
        if: runner.os != 'windows'
        run: |
          if [[ "${{ runner.os }}" = "macOS" ]]
          then
            echo "/usr/local/bin:/usr/bin:/bin" >> "${GITHUB_PATH}"
          else
            echo "/home/linuxbrew/.linuxbrew/bin:/usr/bin:/bin" >> "${GITHUB_PATH}"
          fi

      - name: Uninstall GitHub Actions Homebrew
        run: |
          if which brew &>/dev/null
          then
            /bin/bash uninstall.sh -n >/dev/null
            /bin/bash uninstall.sh -f >/dev/null
          fi

      - run: /bin/bash -c "$(cat install.sh)"

      - run: brew config

      - run: brew install ack

      - run: /bin/bash uninstall.sh -f >/dev/null

      - run: /bin/bash -c "$(cat install.sh)"

      - name: Uninstall and reinstall with sudo NOPASSWD
        if: runner.os == 'linux'
        run: |
          echo "${USER} ALL=(ALL) NOPASSWD:ALL" | sudo tee "/etc/sudoers.d/${USER}"
          /bin/bash uninstall.sh -f >/dev/null
          /bin/bash -c "$(cat install.sh)"

      - name: Check code styles
        if: runner.os != 'windows'
        run: |
          brew install shellcheck shfmt diffutils
          brew style *.sh

      - run: /bin/bash uninstall.sh -n >/dev/null

      - run: /bin/bash uninstall.sh -f >/dev/null
