#!/bin/sh
# SPDX-FileCopyrightText: 2026 Nikolay Govorov
# SPDX-License-Identifier: 0BSD
#MISE description="Verify repository licensing metadata"
#MISE tools={"pipx:reuse"="6.2.0","aqua:EmbarkStudios/cargo-deny"="0.19.0"}

set -eu

check_copyright_headers() {
    invalid_headers=$(
        git grep -n -I -E \
            'Copyright[[:space:]]+(\([cC]\)|©)|SPDX-FileCopyrightText:' \
            -- . \
            ':(exclude)*.md' \
            ':(exclude)LICENSE' \
            ':(exclude)LICENSES/**' \
            ':(exclude)COPYING*' |
            awk 'match($0, /:[0-9]+:/) {
                line = substr($0, RSTART + 1, RLENGTH - 2)
                if (line > 10) {
                    next
                }

                text = substr($0, RSTART + RLENGTH)
                reason = ""
                if (text ~ /^[[:space:]]*((<!--|#|\/\/|\/\*|\*)[[:space:]]*)?Copyright[[:space:]]+(\([cC]\)|©)/) {
                    reason = "legacy copyright header"
                } else if (text ~ /SPDX-FileCopyrightText:($|[^ ]| [[:space:]])/) {
                    reason = "expected exactly one space after colon"
                } else if (text ~ /SPDX-FileCopyrightText:.*Nikolay Govorov/ &&
                           text !~ /SPDX-FileCopyrightText: 2026 Nikolay Govorov([[:space:]]*(\*\/|-->))?$/) {
                    reason = "expected 2026 Nikolay Govorov"
                }

                if (reason != "") {
                    print reason ": " $0
                }
            }'
    )

    if [ -n "$invalid_headers" ]; then
        printf '%s\n%s\n' 'Invalid copyright headers:' "$invalid_headers" >&2
        return 1
    fi
}

check_copyright_headers
reuse lint

if [ -f Cargo.toml ]; then
    cargo-deny check
fi
