#!/bin/sh
# SPDX-FileCopyrightText: 2026 Domantas Adomėlis <legal@denaerium.com>
# SPDX-License-Identifier: MIT OR Apache-2.0

set -u

for cmd in grep date sed git hawkeye cargo; do
    if ! command -v "$cmd" >/dev/null 2>&1; then
        echo "pre-commit: required command '$cmd' not found" >&2
        exit 1
    fi
done

if ! cargo fmt --all --check >/dev/null 2>&1; then
    echo "Formatting issues found. Running cargo fmt..." >&2
    cargo fmt --all
    echo "Files reformatted in working tree. Review, then: git add . && git commit" >&2
    exit 1
fi

if ! cargo clippy --all-targets --all-features -- -D warnings; then
    echo "Clippy found issues. Fix them, then commit." >&2
    exit 1
fi

CONF="licenserc.toml"
CURRENT_YEAR=$(date +%Y)
HEADER_YEAR=$(grep -o 'SPDX-FileCopyrightText: [0-9]\{4\}' "$CONF" | grep -o '[0-9]\{4\}')

if [ -z "$HEADER_YEAR" ]; then
    echo "Could not find header year in $CONF" >&2
    exit 1
fi

if [ "$HEADER_YEAR" != "$CURRENT_YEAR" ]; then
    echo "Header year $HEADER_YEAR != current year $CURRENT_YEAR. Updating..." >&2
    sed -i "s/SPDX-FileCopyrightText: $HEADER_YEAR/SPDX-FileCopyrightText: $CURRENT_YEAR/" "$CONF"
    hawkeye format
    echo "Year bumped to $CURRENT_YEAR and headers regenerated. Review, git add . && git commit" >&2
    exit 1
fi

CHECK_OUT=$(hawkeye check 2>&1)
# shellcheck disable=SC2181
if [ $? -ne 0 ]; then
    echo "$CHECK_OUT" >&2
    echo "License headers invalid. Generating fixes..." >&2
    hawkeye format >/dev/null 2>&1
    echo "Headers written to working tree. Review, then: git add . && git commit" >&2
    exit 1
fi
