#!/bin/sh

##
# Checks the max line length.
#
# 'rustfmt' cannot check the length of the comment.
# (feature 'comment_width' and 'wrap_comments' are unstable so far.)
#
# Because 'max_width' of rustfmt is 100 (= default), alert if "$path" includes line longer than 100.
check_line_length() {
    local path="$1"
    local len=$(awk 'BEGIN { max = 0 } { if (max < length($0)) { max = length($0) } } END {print max}' "$path")

    if [ "$len" -gt 100 ]; then
        echo "The max line length of" "$path" "is greater than 100." >&2
        exit 1
    fi
}

check_license() {
    local path="$1"
    if grep -q "LGPL-3.0-or-later OR Apache-2.0 OR BSD-2-Clause" "$path"; then
        :
    else
        echo "$path" "lacks of the license." >&2
        exit 1
    fi
}

(
    cd `git rev-parse --show-toplevel`

    for f in $(find src -name '*.rs' -type f); do
        check_license "$f"
        check_line_length "$f"
    done

    cargo fmt -- --check || exit "$?"
    cargo test || exit "$?"

    exit 0
)
