#
# Try to find out the right distccd hosts
#
unset HOST_LIST
[ -e /etc/distccd.hosts ] && HOST_LIST=/etc/distccd.hosts
[ -e $HOME/.distccd.hosts ] && HOST_LIST=$HOME/.distccd.hosts
# sorry, SuSE special. Feel free to add your location here ;)
[ -e /work/users/adrian/distccd.hosts ] && HOST_LIST=/work/users/adrian/distccd.hosts

# do we not use the standard port ?
. /etc/sysconfig/distccd
PORT_EXT=""
[ "$DISTCCD_PORT" = 3632 ] || PORT_EXT=":$DISTCCD_PORT" 

if [ -e $HOST_LIST ]; then
   
	export LC_ALL=C
	GCC_VER="`gcc -v 2>&1 |  sed -n 's/gcc version \([^ ]*\).*/\1/p'`"
	ARCH="`sed -n 's@.*(\([^)]*\)).*@\1@p' /etc/SuSE-release`"
	DISTCC_HOSTS="`grep -v ^# $HOST_LIST | sed -n -e \"s/${GCC_VER}-${ARCH}:[ ]*\(.*\)/\1/p\" | head -1 | tr 'A-Z' 'a-z'`"
	[ "$DISTCC_HOSTS" ] || { echo "unsupported compiler, please configure it in /etc/distccd.hosts"; }

	localhost=`hostname | tr 'A-Z' 'a-z'`
        new_hosts=
        for HOST in $DISTCC_HOSTS; do
           if test "$HOST" = "$localhost"; then
                new_hosts="$new_hosts localhost$PORT_EXT"
           else
              if ping -c 1 $HOST >& /dev/null; then
                  new_hosts="$new_hosts $HOST$PORT_EXT"
              else
                  echo "hostname $HOST can not be resolved"
              fi
	   fi
        done
        DISTCC_HOSTS=$new_hosts

	#
	# randomize distccd host order
	#
        NR_OF_HOSTS="`echo $DISTCC_HOSTS|wc -w`"
        i=$NR_OF_HOSTS
	OUT=""
        while [ $i -gt 0 ]; do
          e=$(( $RANDOM * $i / 32767 ))
          j=0
	  IN=""
	  for s in $DISTCC_HOSTS; do
            [ $j -eq $e ] \
              && OUT="$OUT $s" \
	      || IN="$IN $s"
	    j=$(( $j + 1 ))
          done
	  DISTCC_HOSTS=$IN
	  i=$(( $i - 1 ))
        done
	DISTCC_HOSTS=$OUT
        echo setup DISTCC_HOSTS for gcc ${GCC_VER}-${ARCH} \($NR_OF_HOSTS hosts \)
else
  echo 'no host list found (/etc/distccd.hosts)'
fi

#
# setup enviroment for the configure/make stuff
#
export CC=distcc
export CXX=distcc++
export DISTCC_HOSTS

