#! /bin/sh
# $1: package directory
# $2: manifest file

if [ ! -d $1 ]; then
  echoc RED "! package directory does not exists"
  exit 1
fi
if [ ! -f $2 ]; then
  echoc RED "! manifest file does not exists"
  exit 1
fi

cd $1
if [ $? -ne 0 -o ! -d install ]; then
  echoc READ "! package format error"
  exit 1
fi
[ ! -d workdir ] && mkdir workdir

# Build list of files to re-pack
#echo "- computing the list of files to save..."
rm -f workdir/.temperror
> workdir/.templist1
cat $2 | grep -v "^install" | grep -v "^incoming" | while read TFILE
do
  if [ ! -e "/$TFILE" ]; then
    echoc YELLOW "$0: /$TFILE does not exists!"
    >workdir/.temperror
  fi
  [ -d "/$TFILE" ] && continue
  echo "/$TFILE" >>workdir/.templist1
done
> workdir/.templist2
cat $2 | grep "^incoming/" | cut -b 10- | while read TFILE
do
  if [ ! -e "/$TFILE" ]; then
    echoc YELLOW "$0: /$TFILE does not exists!"
    >workdir/.temperror
  fi
  [ -d "/$TFILE" ] && continue
  echo "/$TFILE" >>workdir/.templist2
done
if [ -f workdir/.temperror ]; then
  echoc RED "$0: cannot continue if there are missed files!"
  exit 1
fi

#echo "- saving files ..."
tar -O -p -c -T workdir/.templist1 | tar -x -p
if [ $? -ne 0 ]; then
  echoc RED "$0: error while saving files"
fi
if [ `cat workdir/.templist2 | wc -l` -gt 0 ]; then
	mkdir -p incoming
	tar -O -p -c -T workdir/.templist2 | tar -x -p -C incoming/
	if [ $? -ne 0 ]; then
	  echoc RED "$0: error while saving incoming files"
	fi
fi

# done
exit 0

