name: Workflow Sanity

on:
  push:
    branches:
      - main
  pull_request:

concurrency:
  group: workflow-sanity-${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
  cancel-in-progress: ${{ github.event_name == 'pull_request' }}

jobs:
  no-tabs:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - name: Checkout
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2

      - name: Fail on tabs in workflow files
        run: |
          python - <<'PY'
          from __future__ import annotations

          import pathlib
          import sys

          root = pathlib.Path(".github/workflows")
          bad: list[str] = []
          for path in sorted(root.rglob("*.yml")):
            if b"\t" in path.read_bytes():
              bad.append(str(path))
          for path in sorted(root.rglob("*.yaml")):
            if b"\t" in path.read_bytes():
              bad.append(str(path))

          if bad:
            print("Tabs found in workflow file(s):")
            for path in bad:
              print(f"- {path}")
            sys.exit(1)
          PY

  actionlint:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - name: Checkout
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2

      - name: Install actionlint
        run: |
          set -euo pipefail
          ACTIONLINT_VERSION="1.7.11"
          archive="actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz"
          base_url="https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}"
          curl -sSfL -o "${archive}" "${base_url}/${archive}"
          curl -sSfL -o checksums.txt "${base_url}/actionlint_${ACTIONLINT_VERSION}_checksums.txt"
          grep " ${archive}$" checksums.txt | sha256sum -c -
          tar -xzf "${archive}" actionlint
          sudo install -m 0755 actionlint /usr/local/bin/actionlint

      - name: Lint workflows
        run: actionlint

  scripts-executable:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - name: Checkout
        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2

      - name: Ensure shell scripts are executable and use bash shebang
        run: |
          set -euo pipefail
          bad=0
          while IFS= read -r -d '' path; do
            if [ ! -x "$path" ]; then
              echo "Non-executable script: $path"
              bad=1
            fi
            shebang="$(head -n 1 "$path" || true)"
            if [ "$shebang" != "#!/usr/bin/env bash" ]; then
              echo "Invalid shebang in $path: expected '#!/usr/bin/env bash', got '${shebang:-<empty>}'"
              bad=1
            fi
          done < <(find scripts -type f -name "*.sh" -print0)
          exit "$bad"
