#!/bin/sh
set -e

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

ARCH=${ARCH:-sparc}
BUILD=${BUILD:-0}
VERSION=${VERSION:-1.4.13}

if [ ! -f /usr/include/asm/sun4prom.h ]; then
 # sun4prom.h == a common sparc32-only header file
  echo
  echo "You need to be compiling against SPARC32 headers."
  echo "See readme.build in the build directory."
  echo
  exit
fi

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

rm -rf $PKG
mkdir -p $PKG

# Explode the package framework:
cd $PKG
explodepkg $CWD/_silo.tar.gz

# Unpack sources
cd $TMP
rm -rf silo-$VERSION
echo "+===========+"
echo "| silo-$VERSION |"
echo "+===========+"
tar jxvf $CWD/silo-$VERSION.tar.bz2
cd silo-$VERSION

#zcat $CWD/patches-sparc/silo-1.4.x-ls_c_headerfix-1.diff.gz | \
#  patch -p0 --verbose

zcat $CWD/patches-sparc/silo-1.4.10-megapatch.diff.gz | \
  patch -p1 --verbose

make

mkdir -p $PKG/sbin $PKG/usr/sbin $PKG/etc $PKG/usr/man/man8 \
         $PKG/usr/man/man5 $PKG/usr/man/man1 $PKG/usr/bin
cat silo/silo > $PKG/sbin/silo
cat silo/silocheck > $PKG/usr/sbin/silocheck
cat tilo/maketilo  > $PKG/usr/bin/maketilo
cat tilo/tilo.sh   > $PKG/usr/bin/tilo
chown root.root $PKG/sbin/silo $PKG/usr/sbin/silocheck $PKG/usr/bin/*
chmod 755       $PKG/sbin/silo $PKG/usr/sbin/silocheck $PKG/usr/bin/*

# Strip the binaries?
# Will stripping break binary-internal stuff?

cp etc/silo.conf $PKG/etc/silo.conf-sample
chmod 644 $PKG/etc/silo.conf-sample

( cd man
  cat silo.8 | gzip -9c > $PKG/usr/man/man8/silo.8.gz
  cat silo.conf.5 | gzip -9c > $PKG/usr/man/man5/silo.conf.5.gz 
  cat tilo.1 | gzip -9c > $PKG/usr/man/man1/tilo.1.gz
  cat maketilo.1 | gzip -9c > $PKG/usr/man/man1/maketilo.1.gz)

mkdir -p $PKG/usr/doc/silo-$VERSION
cp COPYING docs/* $PKG/usr/doc/silo-$VERSION

mkdir $PKG/boot
cp -a `find | egrep '\.b$'` $PKG/boot
chmod 644 $PKG/boot/*

mkdir -p $PKG/install
cat $CWD/slack-desc > $PKG/install/slack-desc

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

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