#!/bin/bash

USAGE=$(cat <<-END
USAGE: rpm-rebuild <rpm-package>

This script simply scan a RPM package with kss and insert the resulted digest 
blob into the RPM package.
END
)

function usage() {
	echo "$USAGE"
}

function detect_cmd() {
	if ! command -v $1 &> /dev/null; then
        	echo "Could not find executable $1 in \$PATH."
        	exit 1
	fi
}

detect_cmd rpmrebuild
detect_cmd kss

if [[ $# -eq 0 || -z "$1" ]]; then
	usage
	exit 1
fi

RPM=$1
NVR=${RPM%.*.*}	# strip the suffix

SPEC_FILES_CMD="cat - <(echo \"/etc/digests/$NVR\")"
MODIFY_CMD="	cd \$RPM_BUILD_ROOT; 
		mkdir -p etc/digests; 
		KSS_DEBUG=kss kss digest scan . -d etc/digests -o $NVR"

rpmrebuild 	--change-spec-files="$SPEC_FILES_CMD" \
		--modify="$MODIFY_CMD"	\
		-p "$RPM"
