#!/bin/sh
set -e

ROOTDIR=$(dirname $(readlink -f $0))/..

# busybox grep does not know about --text
if grep --help 2>/dev/null | grep -q -- --text; then
    GREP="grep --text"
else
    GREP=grep
fi

# split preload code into internal logic and libc wrappers
CODE_INT=`grep -B 100000 'Overridden libc' $ROOTDIR/src/libumockdev-preload.c`
CODE_WRAPPERS=`grep -A 100000 'Overridden libc' $ROOTDIR/src/libumockdev-preload.c`

LIBC_OVERRIDES=`echo "$CODE_WRAPPERS" | $GREP '^[a-z_]\+(' | grep -v '^WRAP_' | cut -f1 -d'('`

RET=0

check_empty() {
    [ -z "$1" ] || {
        echo "* $2:" >&2
        echo "---------" >&2
        echo "$R" >&2
        echo "---------" >&2
        echo >&2
        RET=1
    }
}

# internal code must not have any exported (non-static) functions
R=$(echo "$CODE_INT" | $GREP -B1  '^[a-z_]\+(' | awk 'BEGIN { RS="--\n" } !/static/ { print $0 }')
check_empty "$R" "preload internal code part has exported function(s)"

# wrappers must be exported
R=$(echo "$CODE_WRAPPERS" | $GREP -B1  '^[a-z_]\+(' | awk 'BEGIN { RS="--\n" } /static/ { print $0 }')
check_empty "$R" "preload libc wrapped code part has non-exported function(s)"

# wrappers must not have a '_' in the name, libc doesn't use that style
R=$(echo "$LIBC_OVERRIDES" | grep _ | grep -v inotify_add_watch || true)
check_empty "$R" "preload libc wrapped code part exports function with '_'"

# must not use wrapped functions in internal logic
for fn in $LIBC_OVERRIDES; do
    R=$(echo "$CODE_INT" | $GREP -w $fn | $GREP -Ev "(/\*|\"|libc_func|#include|^ \* ).*$fn" || true)
    check_empty "$R" "preload internal code part must not use overridden libc function $fn"
done

exit $RET
