#! /bin/sh

# Just grab dirbase/dir(s)
readbase ()
{
    DIRBASE=$1
    DIRCONTENTS=$2
    for each in $DIRBASE/*
    do
	if test -d $each
	then
	    DIRCONTENTS="$DIRCONTENTS $each"
	fi
    done
    echo $DIRCONTENTS
}

# Prefer subdir/src over subdir, use whichever available
readbase2 ()
{
    DIRBASE=$1
    DIRCONTENTS=$2
    for each in $DIRBASE/*
    do
	if test -d $each
	then
	    if test -d $each/src
	    then
		DIRCONTENTS="$DIRCONTENTS $each/src"
	    else
		DIRCONTENTS="$DIRCONTENTS $each"
	    fi
	fi
    done
    echo $DIRCONTENTS
}

OS=$OSTYPE

if test "x$OS" = x; then 
  echo "please set the environment variable OSTYPE "
  echo "to a value appropriate for your system."
  echo "to do so type: setenv OSTYPE `uname`   for the csh, tcsh"
  echo "               export OSTYPE=`uname`   for other shells"
  exit 1
fi

SRC_DIR=`readbase src src`
SAMPLES_DIR=`readbase2 samples`
UTILS_DIR=`readbase2 utils`
USER_DIR=`readbase2 user`

ALL_DIR="$SRC_DIR $SAMPLES_DIR $UTILS_DIR $USER_DIR"

echo Creating for: $OS

# create defaults
if test ! -d setup/$OS; then
    mkdir setup/$OS
fi

SUBSTFILE=setup/$OS/substit

# the substit file first
if test -f setup/substit ; then
  cat setup/substit | sed "s/*/@/g" > $SUBSTFILE;
  rm -f setup/substit 
fi
# now the template file
cat setup/maketmpl.in | sed -f $SUBSTFILE > setup/$OS/maketmpl

# now the config header file
#if test -f setup/wx_setup.h ; then
#  cat setup/wx_setup.h > setup/$OS/wx_setup.h;
#  rm -f setup/wx_setup.h
#fi

# create lib and bin directory
if test ! -d lib; then
  mkdir lib
fi
if test ! -d lib/$OS; then
  mkdir lib/$OS
fi
if test ! -d bin; then
  mkdir bin
fi
if test ! -d bin/$OS; then
  mkdir bin/$OS
fi

# create makefiles
for each in $ALL_DIR; do
    DIR=$each/$OS
    # create Makefile in directory
    if test -r $each/Makefile.in ; then
        # create directory
        if test ! -d $DIR; then
            echo "Creating Directory: $DIR..."
	    mkdir $DIR
        fi
	echo "Creating: $DIR/Makefile..."
	cat $each/Makefile.in | sed -f $SUBSTFILE > $DIR/Makefile
	(cd $DIR; make subdirs > /dev/null;)
    fi
done
