#!/bin/sh

set -e
PATH=/bin:/usr/bin:$PATH; export PATH
trap "rm -f tmp$$[abcdef].[oc]" 0
target=port_ipv6
new=new_${target}.h
old=${target}.h

cat > tmp$$a.c <<EOF
#include <sys/types.h>
#include <netinet/in.h>
struct sockaddr_in6 xx;
EOF

cat > tmp$$b.c <<EOF
#include <sys/types.h>
#include <netinet/in.h>
struct in6_addr xx;
EOF

cat > tmp$$c.c <<EOF
#include <sys/types.h>
#include <netinet/in.h>

foo() {
	void *a = &in6addr_any;
}
EOF

cat > tmp$$d.c <<EOF
#include <sys/types.h>
#include <sys/socket.h>
struct sockaddr_storage xx;
EOF

cat > tmp$$e.c <<EOF
#include <sys/types.h>
#include <sys/socket.h>
struct sockaddr_storage xx;
main() {
	printf("%u\n", sizeof(xx.ss_family));
}
EOF

cat > tmp$$f.c <<EOF
#include <sys/types.h>
#include <netinet/in.h>
struct sockaddr_in6 xx;
main() { xx.sin6_scope_id = 0; }
EOF

cat > ${new} <<EOF

/* This file is automatically generated. Do Not Edit. */

#ifndef ${target}_h
#define ${target}_h

EOF

if ${CC} -c tmp$$a.c > /dev/null 2>&1
then
        echo "#define HAS_INET6_STRUCTS" >> ${new}
        if ${CC} -c tmp$$b.c > /dev/null 2>&1
        then
		def=
	else
                echo "#define in6_addr in_addr6" >> ${new}
		def="-Din6_addr=in_addr6"
        fi
        if ${CC} $def -c tmp$$c.c > /dev/null 2>&1
        then
		:
	else
		echo "#define NEED_IN6ADDR_ANY" >> ${new}
        fi
	if ${CC} -c tmp$$d.c > /dev/null 2>&1
	then
		if ${CC} -c tmp$$e.c > /dev/null 2>&1
		then
			:
		else
			echo "#define ss_family __ss_family" >> ${new}
		fi
	else
		echo "#define NEED_SOCKADDR_STORAGE" >> ${new}
	fi
	if ${CC} -c tmp$$f.c > /dev/null 2>&1
	then
		echo "#define HAVE_SIN6_SCOPE_ID" >> ${new}
	else
		echo "#undef HAVE_SIN6_SCOPE_ID" >> ${new}
	fi
	case `uname -r` in
	2.0.*)	echo "#define NO_WORKING_IPV6" >> ${new} ;;
	esac
else
        echo "#undef HAS_INET6_STRUCTS" >> ${new}
fi
echo  >> ${new}
echo "#endif" >> ${new}

if [ -f ${old} ]; then
	if cmp -s ${new} ${old} ; then
		rm -f ${new}
	else
		rm -f ${old}
		mv ${new} ${old}
	fi
else
	mv ${new} ${old}
fi
exit 0
