#!/bin/sh

# If using normal root, avoid changing anything.
if [ -z "$RPM_BUILD_ROOT" -o "$RPM_BUILD_ROOT" = "/" ]; then
    echo "RPM_BUILD_ROOT is not set or set to / : skipping create changelog"
    exit 0
fi

if [ "$NO_BRP_CREATE_CHANGELOG" = "true" ]; then
    echo "NO_BRP_CREATE_CHANGELOG is set: skipping create changelog"
    exit 0
fi

for SPECFILES in $(find "$RPM_SOURCE_DIR" -type f -name "*.spec" 2>/dev/null); do
    rm -f "$RPM_SOURCE_DIR/.build-changelog"
    echo "running changelog2spec --target rpm --file $SPECFILES"
    if ! /usr/lib/build/changelog2spec --target rpm --file "$SPECFILES" > "$RPM_SOURCE_DIR/.build-changelog"; then 
        rm -f "$RPM_SOURCE_DIR/.build-changelog"
    fi
    if [ -e "$RPM_SOURCE_DIR/.build-changelog" ]; then
        sed -i -rz 's/(.*%changelog[^\n]*).*/\1\n/' "$SPECFILES"
        cat "$RPM_SOURCE_DIR/.build-changelog" >> "$SPECFILES"
    fi
    rm -f "$RPM_SOURCE_DIR/.build-changelog"
done

if [ -z "$SPECFILES" ]; then
    echo "No .spec files found."
    exit 0
fi
