#!/bin/bash

set -e

CONFIG_PREFIX=${CONFIG_:-CONFIG_}
SED_CONFIG_EXP1="s/^\(${CONFIG_PREFIX}[a-zA-Z0-9_]*\)=.*/\1/p"
SED_CONFIG_EXP2="s/^# \(${CONFIG_PREFIX}[a-zA-Z0-9_]*\) is not set$/\1/p"

YELLOW='\033[0;33m'
NC='\033[0m'

warn() {
    echo -e "${YELLOW}$1${NC}"
}

usage() {
    echo "Usage: $0 CONFIG_FILE FRAGMENT_FILE"
    echo
    echo "Used prefix: '$CONFIG_PREFIX'. You can redefine it with \$CONFIG_ environment variable."
}

if [ "$#" -ne 2 ] ; then
    usage
    exit 1
fi

CONFIG_FILE="$1"
FRAGMENT_FILE="$2"

warn "Checking merged config"

for CFG in $(sed -n -e "$SED_CONFIG_EXP1" -e "$SED_CONFIG_EXP2" "$FRAGMENT_FILE"); do
    REQUESTED_VAL=$(grep -w -e "$CFG" "$FRAGMENT_FILE")
    ACTUAL_VAL=$(grep -w -e "$CFG" "$CONFIG_FILE" || true)
    if [ "x$REQUESTED_VAL" != "x$ACTUAL_VAL" ] ; then
        warn "Value requested for $CFG not in final .config"
        warn "Requested value:  $REQUESTED_VAL"
        warn "Actual value:     $ACTUAL_VAL"
        echo ""
    fi
done

warn "Finished checking merged config"
