#!/bin/sh
# Package Repack
# @1996,97,98,99,2000 by Antonio Gallo
# This script rebuild a package that is present into the ports
# structure from the files present into the filesystem


# Include BPP options
. package.conf


# Check parameters
if [ "$1" = "" ]; then
  echoc CYAN "Bad Penguin - Package Repack $PKG_VERSION"
  echoc RED  "Sorry, you did'nt specified a package name"
  exit 1
fi

# Banner
echoc CYAN "Repacking $1"

# Exit if no port
if [ ! -d $PKG_PORTS/$1 ]; then
  echoc RED "Package $1 is not available as port"
  exit 1
fi
# Exit if there is no MANIFEST
if [ ! -f $PKG_PORTS/$1/MANIFEST ]; then
  echoc RED "Package $1 cannot be repacked (no MANIFEST)"
  exit 1
fi

# Make temp directory
TEMPDIR="/var/tmp/`tempname`"
if [ -d $TEMPDIR ]; then
  echoc RED "Directory $TEMPDIR already exists"
  exit 1
fi
# Setup the trap :-)
EXITCODE=1
trap 'rm -fR $TEMPDIR ; exit $EXITCODE' 0

echo "Preparing package's directory ..."
mkdir -p $TEMPDIR
mkdir $TEMPDIR/install
cp $PKG_PORTS/$1/* $TEMPDIR/install
if [ $? -ne 0 ]; then
  echoc RED "Error copying ports file"
  exit 1
fi

echo "Compressing some package's files ..."
cat $PKG_PORTS/$1/MANIFEST | while read FILENAME ; do
  case $FILENAME in
    *gz)
      if [ ! -f /$FILENAME ]; then
        echo "- compressing /$FILENAME"
        gzip -9 `dirname /$FILENAME`/`basename $FILENAME .gz`
        if [ $? -ne 0 ]; then
          echoc RED "Error compressing file"
          exit 1
        fi
      fi
    ;;
  esac
done

echo "Preparing package's files ..."
( cd / ; tar -O -p -T $PKG_PORTS/$1/MANIFEST -c | tar -v -x -p -C $TEMPDIR )
if [ $? -ne 0 ]; then
  echoc RED "Error while porting files"
  exit 1
fi

EXITCODE=0
echoc GREEN "Package $1 have been repacked under $TEMPDIR"
exit
