#!/usr/bin/env bash
# Formatter: Shell — shfmt + shellcheck
# Contract: $1 = absolute file path, format in place, lint, exit 0 if clean / 1 if errors
# Missing tools: exit 0 silently

FILE="$1"
[ -z "$FILE" ] && exit 0
[ -f "$FILE" ] || exit 0

HAD_ERRORS=0

# Format with shfmt if available
if command -v shfmt >/dev/null 2>&1; then
    shfmt -w "$FILE" 2>/dev/null
fi

# Lint with shellcheck if available
if command -v shellcheck >/dev/null 2>&1; then
    ERRORS=$(shellcheck -f gcc "$FILE" 2>&1)
    if [ $? -ne 0 ]; then
        echo "$ERRORS" >&2
        HAD_ERRORS=1
    fi
fi

# If neither tool is installed, silently pass
if ! command -v shfmt >/dev/null 2>&1 && ! command -v shellcheck >/dev/null 2>&1; then
    exit 0
fi

exit $HAD_ERRORS
