name: Shell Lint & Format

on:
  push:
    paths:
      - "**/*.sh"
      - "**/*.bash"
      - "**/*.zsh"
      - "**/.bashrc"
      - "**/.bash_profile"
      - "**/.profile"
      - "**/.bash_logout"
      - "**/.bash_aliases"
      - "**/.zshrc"
      - "**/.zprofile"
      - "**/.zshenv"
      - "**/.zlogin"
      - "**/.zlogout"
      - ".github/workflows/shellcheck.yml"
  pull_request:
    paths:
      - "**/*.sh"
      - "**/*.bash"
      - "**/*.zsh"
      - "**/.bashrc"
      - "**/.bash_profile"
      - "**/.profile"
      - "**/.bash_logout"
      - "**/.bash_aliases"
      - "**/.zshrc"
      - "**/.zprofile"
      - "**/.zshenv"
      - "**/.zlogin"
      - "**/.zlogout"
      - ".github/workflows/shellcheck.yml"
  workflow_dispatch:
    inputs:
      apply_fixes:
        description: "Format *.sh and *.bash files and commit changes back to this branch"
        required: false
        default: false
        type: boolean

permissions:
  contents: write
  checks: write
  pull-requests: write

jobs:
  shell:
    name: ShellCheck, shfmt, and shell syntax
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          ref: ${{ github.ref }}

      - name: ShellCheck real shell scripts
        uses: reviewdog/action-shellcheck@v1
        with:
          fail_level: warning
          reporter: github-check
          path: "."
          pattern: "*.sh"
          check_all_files_with_shebangs: "false"
          shellcheck_flags: "--external-sources"

      - name: Install syntax and formatter tools
        run: |
          sudo apt-get update
          sudo apt-get install -y shfmt zsh

      - name: Check shell syntax
        shell: bash
        run: |
          set -euo pipefail
          bash -n bashrc/.bashrc
          bash -n bashprofile/.bash_profile
          bash -n flutter/install-flutter.sh
          bash -n polybar/.config/polybar/launch_polybar.sh
          sh -n git/setup-git.sh
          sh -n rofi/.config/rofi/powermenu.sh
          zsh -n zsh/.zshrc
          zsh -n zprofile/.zprofile

      - name: Check shfmt formatting
        if: ${{ github.event_name != 'workflow_dispatch' || inputs.apply_fixes != true }}
        run: shfmt -d -i 4 -ci flutter/install-flutter.sh git/setup-git.sh polybar/.config/polybar/launch_polybar.sh rofi/.config/rofi/powermenu.sh

      - name: Apply shfmt formatting
        if: ${{ github.event_name == 'workflow_dispatch' && inputs.apply_fixes == true }}
        run: shfmt -w -i 4 -ci flutter/install-flutter.sh git/setup-git.sh polybar/.config/polybar/launch_polybar.sh rofi/.config/rofi/powermenu.sh

      - name: Commit formatting fixes
        if: ${{ github.event_name == 'workflow_dispatch' && inputs.apply_fixes == true }}
        uses: stefanzweifel/git-auto-commit-action@v7
        with:
          commit_message: Apply shell formatting
