#!/bin/sh
#
# p11 - pdp11 emulator; Copyright (C) 1994 Hartmut Brandt, Joerg Micheel 
# see the file LICENSE for further information
#
#
# the configurations in this list must be separated by spaces
#
CONFIGS="i386-bsdi sparc-sunos sparc-solaris"

#
# need an ANSI-CPP which doesn't include any system files or define variables
#
#CPP="cccp -P -undef -nostdinc"
CPP="gcc -x c -P -undef -nostdinc -E"

#
# save command for later use
#
VERBOSE=No
USE_SAVED=No

#
# print help
#
help() {
	echo 1>&2 "Usage: config machine-system"
	echo 1>&2
	echo 1>&2 "known configurations:"
	for i in ${CONFIGS} ; do
		echo 1>&2 "	$i"
	done
	exit 1
}

error() {
	echo 1>&2 $*
	exit 2
}

#
# parse and shift off options
#
while [ $# -ne 0 ] ; do
  case $1 in
  -h|--help)
	help
	exit 1
	;;
  -v|--verbose)
	VERBOSE=Yes
	;;
  -s|--saved)
	USE_SAVED=Yes
	;;
  -p|-print)
	if [ -f .config ] ; then
	  cat .config
	  exit 0
    	else
	  error "Saved configuration file not found"
        fi
	;;
  -*)	error "Unknown flag $1"
	;;
  *)	break
	;;
  esac
  shift
done

#
# there must be exactly one arg left
#
if [ ${USE_SAVED} = Yes ] ; then
  if [ -f .config ] ; then
    CONF=
    if read <.config CONF ; then
      if [ "${CONF}" = "" ] ; then
        error "can't read saved configuration file"
      fi
    else
      error "can't read saved configuration file"
    fi
  else
    error "Saved configuration file not found"
  fi
else
  if [ $# -ne 1 ] ; then
    help
  else
    CONF=$1
  fi
fi

#
# check if configuration is ok
#
case ${CONF} in
  *-*)	;;
  *)	error "bad configuration: need machine-system"
	;;
esac

CONFIG=""
for i in ${CONFIGS} ; do
  if [ /$i/ = /${CONF}/ ] ; then
    CONFIG=$i
    break
  fi
done

if [ /${CONFIG}/ = // ] ; then
  error "unknown configuration ${CONF}. Use 'config -help' to get a list."
fi

#
# parse of parts
#
OIFS=${IFS}
IFS=-
set ${CONF}
MACHINE=${1}
SYSTEM=${2}
IFS=${OIFS}

echo machine: ${MACHINE}
echo system:  ${SYSTEM}

#
# make links (remove existing ones)
#
rm -f system.h system.c machine.h Makefile.mach regi.h float.h
ln -s Config/s-${SYSTEM}.h system.h
ln -s Config/s-${SYSTEM}.c system.c
ln -s Config/m-${MACHINE}.h machine.h
ln -s Config/r-${MACHINE}.h regi.h
if [ -f Config/f-${MACHINE}.h ] ; then
  ln -s Config/f-${MACHINE}.h float.h
fi
ln -s Config/M-${MACHINE}-${SYSTEM} Makefile.mach

#
# directory for p11 includes and makefile cpp-includes
INCL=`pwd`

#
# generate Makefiles
#
FILES=`find . -name Makefile.in -print`


for i in ${FILES} ; do
  DIR=`dirname $i`
  (
    cd ${DIR}
    if [ ${VERBOSE} = Yes ] ; then
      pwd
      set -x
    fi
    ${CPP} -I${INCL} -DMAKE_CONFIG="${CONF}" -DMAKE_P11INCL=\'\"${INCL}\"\' Makefile.in >Makefile
  )
done

#
# generate config saved configuration file
#
echo ${MACHINE}-${SYSTEM} >.config

echo "Don't forget to 'gmake deps'."
