#! /bin/sh
#set -x

S_TMP=${S_TMP:-$SHOME/tmp}
tmp_chapter=tmp_chapter$$

prog=$0
Usage() 
{
    echo "$prog <chapter>"
}
Cleanup() {
	rm -rf ${S_TMP}/${tmp_chapter}    
}

if [  $# -le 0 -o $# -gt 2 ]; then
	Usage
	exit 0
fi

while [ $# -gt 0 ] 
do
    case $1 in
	*) chapter=$1
	   shift
	   ;;
    esac
done

if [ x"${SHOME}" = x ]; then
    echo "error: SHOME is not set."
    exit 1
fi

	   
	platform=`$SHOME/cmd/PLATFORM`
    cd ${chapter}
    # Make sure chapter is an absolute path
    chapter=`pwd`
    cd .Data; 

    # 
    # Move .Help .Data before doing dumpForObjects(), since objectnames
    # can legally begin with '.' in Splus.  Don't need to worry about
    # __Shelp - not legal S object names.
    #
    # TODO:  .Help will hopefully be phased out in the future making this
    # step uneccessary.  -sea.
    #
    test -d .Help && mv .Help ..

    cd ${chapter}
    echo ""
    echo "Making __Objects in $chapter/.Data..."
    # make an S chapter
    cd ${S_TMP}
    mkdir $tmp_chapter
    cd $tmp_chapter
	if [ $platform = WIN386 ]; then
		CWD=`pwd`
		TMP_WORK=${S_TMP}/$tmp_chapter
		SCMD="$SHOME/cmd/Sqpe S_HOME=$SHOME S_WORK=$TMP_WORK S_CWD=$CWD"
		SCHAPTCMD="$SHOME/cmd/CHAPTER -d $TMP_WORK"
	else
		SCMD=$SHOME/cmd/Splus
		SCHAPTCMD="$SCMD CHAPTER"
	fi
	$SCHAPTCMD

    # create new all.Sdata, meta.Sdata, and help.Sdata
    echo "Creating all.Sdata, meta.Sdata, and help.Sdata"
    S_CMD_FILE=cmdfile.$$
    cat << EOF > ${S_CMD_FILE}
attach("${chapter}",pos=2)
dumpForObjects(where=2, meta=0)
dumpForObjects(where=2, meta=1)
EOF
    $SCMD < ${S_CMD_FILE}

    # clean out .Data directory before we boot the chapter
    rm -rf .Data
    $SCHAPTCMD

    echo "Booting ${chapter}..."
    BOOTING_S=TRUE; export BOOTING_S
    echo "stop(\"This should not run.\")" | $SCMD
    unset BOOTING_S

    cd ${chapter}
    test -d .Data.orig && rm -rf .Data.orig
    test -d .Data && mv .Data .Data.orig
    echo "copying .Data directory to ${chapter}"
	if [ $platform = WIN386 ]; then
		cp -r ${S_TMP}/${tmp_chapter}/.Data .
	else
    (cd ${S_TMP}/${tmp_chapter}; tar -cf - ./.Data) | tar -xf -
	fi

    # 
    # move .Help directory back into .Data.orig
    # See TODO above.
    #
    if [ -d .Help ]; then
	mv .Help .Data.orig
    fi
	if [ $platform != WIN386 ]; then
    # 
    # Move __Shelp and __Hhelp (if any) from .Data.orig to .Data and then mkdir __Hhelp
    #
    (cd .Data.orig; tar -cf - ./__Shelp) | (cd .Data; tar -xf - )
    [ ! -d .Data/__Hhelp ] && mkdir .Data/__Hhelp && chmod a+w .Data/__Hhelp
	$SHOME/adm/cmd/COPY_DATA_ORIG __Hhelp
	$SHOME/adm/cmd/COPY_DATA_ORIG __Jhelp
	test $sigs && trap "" $sigs
	fi
Cleanup


