#!/bin/sh

if [ -n "$SKIP_LINT" ] ; then
    echo "skipping markdown checks because SKIP_LINT is defined"
    exit 0
fi

# This script will pass provided arguments to markdownlint (mdl), with
# Kramdown warnings enabled, but with the GitLab-specific (and
# non-standard) [[_TOC_]] blob removed. This only works on single
# files, if provided a directory, it will just throw the entire thing
# at mdl.
for path in "$@"; do
    if [ -d "$path" ]; then
        echo "checking directory $path..."
        mdl "$path"
    elif ! [ -e "$path" ]; then
        echo "file $path does not exist, maybe it was removed or renamed? skipping."
    else
        # this could be a symlink, a normal file, or whatever, but it exists
        case "$path" in
            *.md|*.mdwn|*.markdown)
                echo "checking file $path..."
                # this also removes [x] style checklists which kramdown doesn't like
                sed 's/^\[\[_TOC_\]\]/TOC_PLACEHOLDER/;s/^ *\([*-]\|[0-9][0-9]*\.\)  *\[[x ]\] /\* /' "$path" | mdl - ;;
        esac
    fi
done