#!/usr/bin/bash
#shellcheck disable=SC1090

. "$(sfpath)" || exit 3

shellfu import pretty

usage() {
    mkusage "$@" \
        "[options] SRC DST"
}

waiversct() {
    #
    # Create waivers section
    #
    local relpath=$1
    local waivers
    local wtitle="Waivers"
    waivers=$(
        grep -n '#WAIVER:' -r "src/$relpath" \
          | sed "s|^src/$relpath/||" \
          | grep .
    ) || return 1
    think " .. adding waivers"
    echo
    echo "$wtitle"
    echo "${wtitle//?/-}"
    echo
    #shellcheck disable=SC2001
    sed 's/^/    /' <<<"$waivers"
    echo
    echo
}

mktree() {
    #
    # Create doc tree from src to $Dst
    #
    local srcfile
    local relpath
    local dstfile
    local testid
    local suiteid
    local testlink
    suiteid=$(jattool sfind -f id src)
    mkdir -p "$Dst"
    dstfile=$Dst/suite.md
    {
        think "writing: $dstfile"
        echo "$suiteid"
        echo "${suiteid//?/=}"
        find src -type f -name test \
          | sort \
          | while read -r srcfile; do
                relpath=${srcfile#src/}; relpath=${relpath%/test}
                testid="$suiteid$relpath"
                testlink="$relpath [¶](#${relpath////-})"
                think "adding: $testid"
                echo
                echo '<article>'
                echo
                sfdoc -h '[[:lower:]_].*' -e markdown "$srcfile" \
                  | sed "
                        1s|.*|$testlink|
                        2s|.*|${testlink//?/=}|
                    "
                waiversct "$relpath"
                echo '</article>'
            done
    } > "$dstfile"
}

main() {
    local Dst
    local version
    #shellcheck disable=SC2034
    while true; do case $1 in
        -d) PRETTY_DEBUG=true;   shift ;;
        -v) PRETTY_VERBOSE=true; shift ;;
        -*) usage -u "$1" ;;
        *)  break ;;
    esac done
    "$JATTOOL_TDK/utils/mkit/make" _mkit_data >&/dev/null
    version=$(cat .mkit/semver) || {
        version="_jatdoc_no_version_"
        warn "could not find out version"
    }
    Dst="jatdoc/$version"
    debug -v Dst
    mktree
    echo r:jatdoc >>.mkit/built.lst
}

main "$@"
