name: Script Checks

on:
  push:
    paths:
      - "**/*.sh"
      - "**/.bashrc"
      - "**/.bash_profile"
      - "**/.profile"
      - "**/.bash_logout"
      - "**/.bash_aliases"
      - "**/.zshrc"
      - "**/.zprofile"
      - "**/.zshenv"
      - "**/.zlogin"
      - "**/.zlogout"
      - ".github/workflows/shellcheck.yml"
  pull_request:
    paths:
      - "**/*.sh"
      - "**/.bashrc"
      - "**/.bash_profile"
      - "**/.profile"
      - "**/.bash_logout"
      - "**/.bash_aliases"
      - "**/.zshrc"
      - "**/.zprofile"
      - "**/.zshenv"
      - "**/.zlogin"
      - "**/.zlogout"
  workflow_dispatch:

jobs:
  shellcheck:
    name: Shellcheck
    runs-on: ubuntu-latest
    steps:
      - name: Checkout sources
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Run ShellCheck
        uses: reviewdog/action-shellcheck@v1
        with:
          reviewdog_flags: "-fail-level=any"
          path: |
            **/*.sh
            **/.bashrc
            **/.bash_profile
            **/.profile
            **/.bash_logout
            **/.bash_aliases
            **/.zshrc
            **/.zprofile
            **/.zshenv
            **/.zlogin
            **/.zlogout

  shfmt:
    name: Shell Formatting
    runs-on: ubuntu-latest
    needs: shellcheck
    steps:
      - name: Checkout sources
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install shfmt
        run: |
          sudo apt-get update
          sudo apt-get install -y shfmt

      - name: Run shfmt to format shell scripts
        run: |
          set -eu
          shopt -s globstar nullglob
          files=( **/*.sh **/.bashrc **/.bash_profile **/.profile **/.bash_logout **/.bash_aliases **/.zshrc **/.zprofile **/.zshenv **/.zlogin **/.zlogout )
          if [ ${#files[@]} -gt 0 ]; then
            printf 'Formatting %d files\n' "${#files[@]}"
            shfmt -i 4 -w "${files[@]}"
          else
            echo "No shell files to format"
          fi

      - name: Commit and push formatted scripts
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          if ! git diff --quiet; then
            git add .
            git commit -m "Apply shell script formatting"
            git push
          else
            echo "No changes to commit"
          fi
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
