#!/bin/sh
# mkpackage.sh DIRECRORY VERSION

if [ "$2" = "" ]; then
    echo USAGE: $0 DIRECTORY VERSION
    echo Example: $0 algebra 0.48
    exit
else
    DIR=`echo $1 | sed -e 's/\\/$//'| sed -e 's/.tar.gz$//'`
    VER=$2
    DIRVER=$DIR-$VER
    TGZ=$DIRVER.tar.gz

    if [ -d $DIRVER ]; then
	echo $DIRVER already exists.
	exit
    fi
fi


if [ -f $TGZ ]; then
    echo "$TGZ exits overwrite (NONE|y|Y|b|B|n|N)?"
    read ANS
    if [ "$ANS" != "" -a "$ANS" != y -a "$ANS" != Y ]; then
	if [ "$ANS" = b -o "$ANS" = B ]; then
	    echo "$TGZ BACKUPED AS $TGZ.bak."
	    mv $TGZ $TGZ.bak
	else
	    echo STOP.
	    exit
	fi
    fi
fi

if [ -d $DIR ]; then
    BAK=$DIR/*~
    BAKBAK=$DIR/*/*~
    SBAK=$DIR/#*

    if [ "$BAK" != "`echo $BAK`" ]; then
	echo rm -f $BAK
	rm -f $BAK
    fi
    if [ "$BAKBAK" != "`echo $BAKBAK`" ]; then
	echo rm -f $BAKBAK
	rm -f $BAKBAK
    fi
    if [ "$SBAK" != "`echo $SBAK`" ]; then
	echo rm -f $SBAK
	rm -f $SBAK
    fi

#    echo mv $DIR $DIRVER
#    mv $DIR $DIRVER
    echo cp -rf $DIR $DIRVER
    cp -rf $DIR $DIRVER

    if [ -d $DIRVER ]; then

	tar cfvz $TGZ $DIRVER > /dev/null
	echo $TGZ CREATED.

#	echo mv $DIRVER $DIR
#	mv $DIRVER $DIR
	echo rm -rf $DIRVER
	rm -rf $DIRVER
    fi
else
  echo $DIR not exists.
  exit
fi
