#!/bin/bash
set -e

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

# 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_]\+(' | 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
