#!/usr/bin/env bash
# cc-ci lint/format entrypoint (Phase 1b, RL1).
#
#   scripts/lint.sh          # check-only (CI mode): non-zero exit if anything is unclean
#   scripts/lint.sh --fix    # auto-format + apply auto-fixable lints in place
#
# Tools come from the `lint` devshell (`nix develop .#lint`); the `.drone.yml` lint stage runs
# this exact script. Covers: Nix (nixpkgs-fmt/statix/deadnix), Python (ruff), Shell
# (shfmt/shellcheck), YAML (yamllint). Run from the repo root.
set -uo pipefail

cd "$(dirname "$0")/.." || exit 1

FIX=0
[ "${1:-}" = "--fix" ] && FIX=1

# shfmt style: 2-space indent, indent switch cases (matches the existing scripts).
SHFMT_FLAGS=(-i 2 -ci)

fail=0
section() { printf '\n=== %s ===\n' "$1"; }
note() { printf '  %s\n' "$1"; }

# Nix files (exclude the `secrets/` submodule).
mapfile -t NIX_FILES < <(find . -name '*.nix' -not -path './.git/*' -not -path './secrets/*' | sort)
# Shell scripts.
mapfile -t SH_FILES < <(find . -name '*.sh' -not -path './.git/*' -not -path './secrets/*' | sort)

section "Nix — nixpkgs-fmt"
if [ "$FIX" = 1 ]; then
  nixpkgs-fmt "${NIX_FILES[@]}" || fail=1
else
  nixpkgs-fmt --check "${NIX_FILES[@]}" || {
    note "run: scripts/lint.sh --fix"
    fail=1
  }
fi

section "Nix — statix"
if [ "$FIX" = 1 ]; then
  statix fix . || fail=1
else
  statix check . || fail=1
fi

section "Nix — deadnix"
if [ "$FIX" = 1 ]; then
  deadnix --edit "${NIX_FILES[@]}" || fail=1
else
  deadnix --fail "${NIX_FILES[@]}" || fail=1
fi

section "Python — ruff format"
if [ "$FIX" = 1 ]; then
  ruff format . || fail=1
else
  ruff format --check . || {
    note "run: scripts/lint.sh --fix"
    fail=1
  }
fi

section "Python — ruff check"
if [ "$FIX" = 1 ]; then
  ruff check --fix . || fail=1
else
  ruff check . || fail=1
fi

if [ "${#SH_FILES[@]}" -gt 0 ]; then
  section "Shell — shfmt"
  if [ "$FIX" = 1 ]; then
    shfmt "${SHFMT_FLAGS[@]}" -w "${SH_FILES[@]}" || fail=1
  else
    shfmt "${SHFMT_FLAGS[@]}" -d "${SH_FILES[@]}" || {
      note "run: scripts/lint.sh --fix"
      fail=1
    }
  fi

  section "Shell — shellcheck"
  shellcheck "${SH_FILES[@]}" || fail=1
fi

section "YAML — yamllint"
yamllint -c .yamllint.yaml .drone.yml || fail=1

echo
if [ "$fail" = 0 ]; then
  echo "lint: PASS"
else
  echo "lint: FAIL"
fi
exit "$fail"
