#!/usr/bin/env bash
#===============================================================================
# Script Name  : shellcheck-wrapper.sh
# Description  : Wrapper for ShellCheck with project defaults
# Version      : 1.0.0
#===============================================================================

set -Eeuo pipefail

readonly SCRIPT_NAME="${0##*/}"

### Display usage
usage() {
    cat <<EOF
Usage: ${SCRIPT_NAME} <script.sh> [shellcheck-options...]

Runs ShellCheck with recommended settings for production Bash scripts.

Default flags applied:
  -x          Follow source statements
  -s bash     Shell dialect: bash
  -S style    Minimum severity: style (catch everything)

Examples:
  ${SCRIPT_NAME} myscript.sh
  ${SCRIPT_NAME} myscript.sh -S warning    # Only warnings and above
  ${SCRIPT_NAME} *.sh                       # Check multiple files

EOF
}

### Check ShellCheck is installed
check_shellcheck() {
    if ! command -v shellcheck &>/dev/null; then
        echo "ERROR: shellcheck not found. Install with:" >&2
        echo "  Ubuntu/Debian: apt install shellcheck" >&2
        echo "  macOS:         brew install shellcheck" >&2
        echo "  Windows:       scoop install shellcheck" >&2
        exit 3
    fi
}

main() {
    if [[ $# -lt 1 ]] || [[ "$1" == "-h" ]] || [[ "$1" == "--help" ]]; then
        usage
        exit 0
    fi

    check_shellcheck

    local script="$1"
    shift

    if [[ ! -f "$script" ]]; then
        echo "ERROR: File not found: $script" >&2
        exit 5
    fi

    echo "Running ShellCheck on: $script"
    echo "========================================"

    # > Run with defaults + any user-provided options
    # shellcheck disable=SC2086
    shellcheck -x -s bash -S style "$@" "$script"

    local exit_code=$?

    if [[ $exit_code -eq 0 ]]; then
        echo "========================================"
        echo "✓ No issues found"
    else
        echo "========================================"
        echo "✗ ShellCheck found issues (exit code: $exit_code)"
    fi

    exit $exit_code
}

main "$@"
