#!/bin/sh

############################################################
# Copyright (c) 2009-2010 by Aleksey Cheusov
#
# See LICENSE file in the distribution.
############################################################

set -e

LC_ALL=C
export LC_ALL

: ${CHECK_COMMON_SH_DIR:=/usr/pkg/libexec/mk-configure}

##################################################
# options
usage (){
    cat <<EOF
mkc_check_sizeof detects sizeof(type)
by compiling a test program.
mkc_check_sizeof doesn't run a generated executable
and therefore is ready for cross-compiling.

Usage: mkc_check_sizeof type [headers...]

Examples:
   mkc_check_sizeof 'void*'
   mkc_check_sizeof long-long
   mkc_check_sizeof size_t stdlib.h
EOF
}

if test $# -eq 0; then
    usage
    exit 1
fi
if test "_$1" = '_-h'; then
    usage
    exit 0
fi

##################################################
# initializing

type=`echo $1 | tr ' -' '  '`
pathpart=sizeof_`echo $type | tr '* ' 'P~'`
shift

. ${CHECK_COMMON_SH_DIR}/mkc_check_common.sh

##################################################
# test

try_it (){
    # succeedes if size is bad
    # $1 - test size
    # $2.. - #includes
    sz=$1
    shift

    get_includes "$@" > "$tmpc"
    cat >> "$tmpc" <<EOF
void func(void)
{
   switch (0){
      case sizeof ($type): break;
      case $sz:            break;
   }
}
EOF

    if $CC -c -o "${tmpo}" $CPPFLAGS $CFLAGS "${tmpc}" 2>"${tmperr}"; then
    	return 0
    else
    	return 1
    fi
}

check_itself (){
    if try_it 2147483647 "$@"
    then
	for sz in 4 8 2 1 16 12    3 5 6 7 9 10 11 13 14 15; do
	    if try_it $sz "$@"
	    then
		:
	    else
		echo $sz
		return
	    fi
	done
    fi
    echo failed
}

check_and_cache "checking for sizeof ${type}" "$cache" "$@"

##################################################
# clean-ups

cleanup

##################################################
# finishing

printme "$ret\n" 1>&2
echo $ret
