#!/bin/sh
# Set initial variables:
CWD=`pwd`
if [ "$TMP" = "" ]; then
  TMP=/tmp
fi
PKG=$TMP/package-genpower

if [ ! -d $TMP ]; then
  mkdir -p $TMP # location to build the source
fi
rm -rf $PKG
mkdir -p $PKG

VERSION=${VERSION:-1.0.5}
ARCH=${ARCH:-i486}
BUILD=${BUILD:-1}

cd $TMP
rm -rf genpower-$VERSION
tar xzvf $CWD/genpower-$VERSION.tar.gz
cd genpower-$VERSION

chown -R root:root .
find . -perm 666 -exec chmod 644 {} \;
find . -perm 664 -exec chmod 644 {} \;
find . -perm 600 -exec chmod 644 {} \;
find . -perm 444 -exec chmod 644 {} \;
find . -perm 400 -exec chmod 644 {} \;
find . -perm 440 -exec chmod 644 {} \;
find . -perm 777 -exec chmod 755 {} \;
find . -perm 775 -exec chmod 755 {} \;
find . -perm 511 -exec chmod 755 {} \;
find . -perm 711 -exec chmod 755 {} \;
find . -perm 555 -exec chmod 755 {} \;

find . -type d -name CVS -exec rm -rf {} \;

zcat $CWD/genpower.var.diff.gz | patch -p1 -E --verbose || exit 1
make || exit 1
mkdir -p $PKG/sbin
cat genpowerd > $PKG/sbin/genpowerd
cat gentest > $PKG/sbin/gentest
cat genpowerfail > $PKG/sbin/genpowerfail
mkdir -p $PKG/etc
cat genpowerd.conf > $PKG/etc/genpowerd.conf.new
chmod 755 $PKG/sbin/*

( cd $PKG
  find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
  find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
)

mkdir -p $PKG/usr/man/man8
cat genpowerd.8 | gzip -9c > $PKG/usr/man/man8/genpowerd.8.gz
cat gentest.8 | gzip -9c > $PKG/usr/man/man8/gentest.8.gz

mkdir -p $PKG/usr/doc/genpower-$VERSION
cp -a \
  COPYING Change.Log README TODO genpower.docs cables \
  $PKG/usr/doc/genpower-$VERSION

mkdir -p $PKG/install
cat << EOF > $PKG/install/doinst.sh
#!/bin/sh
config() {
  NEW="\$1"
  OLD="\$(dirname \$NEW)/\$(basename \$NEW .new)"
  # If there's no config file by that name, mv it over:
  if [ ! -r \$OLD ]; then
    mv \$NEW \$OLD
  elif [ "\$(cat \$OLD | md5sum)" = "\$(cat \$NEW | md5sum)" ]; then # toss the redundant copy
    rm \$NEW
  fi
  # Otherwise, we leave the .new copy for the admin to consider...
}
config etc/genpowerd.conf.new
EOF
cat $CWD/slack-desc > $PKG/install/slack-desc


# Build the package:
cd $PKG
makepkg -l y -c n $TMP/genpower-$VERSION-$ARCH-$BUILD.tgz

# Clean up the extra stuff:
if [ "$1" = "--cleanup" ]; then
  rm -rf $TMP/genpower-$VERSION
  rm -rf $PKG
fi