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

PKG=$TMP/package-dhcp

if [ ! -d $TMP ]; then
  mkdir -p $TMP # location to build the source
fi
if [ ! -d $PKG ]; then
  mkdir -p $PKG # place for the package to be built
fi

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

echo "+=============+"
echo "| dhcp-2.0pl5 |"
echo "+=============+"
cd $TMP
tar xzvf $CWD/dhcp-2.0pl5.tar.gz
cd dhcp-2.0pl5
./configure linux-2.2
make -j 2
DOCDIR=$PKG/usr/doc/dhcp-2.0pl5
mkdir -p $DOCDIR
cp -a CHANGES README RELNOTES TODO $DOCDIR
mkdir -p $DOCDIR/examples
cp -a client/dhclient.conf server/dhcpd.conf \
  $DOCDIR/examples
chown -R root.root $DOCDIR
cat << EOF > $PKG/etc-incoming/dhcpd.conf
# dhcpd.conf
#
# Configuration file for ISC dhcpd (see 'man dhcpd.conf')
#
EOF
cat << EOF > $PKG/etc-incoming/dhclient.conf
# dhclient.conf
#
# Configuration file for ISC dhclient (see 'man dhclient.conf')
#
EOF
cat client/scripts/linux > $PKG/etc-incoming/dhclient-script
chmod 700 $PKG/etc-incoming/dhclient-script
strip server/dhcpd client/dhclient relay/dhcrelay
cat server/dhcpd > $PKG/usr/sbin/dhcpd
cat relay/dhcrelay > $PKG/usr/sbin/dhcrelay
cat client/dhclient > $PKG/sbin/dhclient
mkdir -p $PKG/usr/man/man5
mkdir -p $PKG/usr/man/man8
for dir in client server ; do
  cd $dir
  for file in *.5 ; do
    cat $file | sed -e "s#ETCDIR#/etc#g" -e "s#DBDIR#/var/db#g" \
      -e "s#RUNDIR#/var/run#g" | gzip -9c > $PKG/usr/man/man5/$file.gz
  done
  for file in *.8 ; do
    cat $file | sed -e "s#ETCDIR#/etc#g" -e "s#DBDIR#/var/db#g" \
      -e "s#RUNDIR#/var/run#g" | gzip -9c > $PKG/usr/man/man8/$file.gz
  done
  cd ..
done
cat relay/dhcrelay.8 | sed -e "s#ETCDIR#/etc#g" -e "s#DBDIR#/var/db#g" \
  -e "s#RUNDIR#/var/run#g" | gzip -9c > $PKG/usr/man/man8/dhcrelay.8.gz

echo "+===================+"
echo "| dhcpcd-1.3.20-pl0 |"
echo "+===================+"
cd $TMP
tar xzvf $CWD/dhcpcd-1.3.20-pl0.tar.gz
cd dhcpcd-1.3.20-pl0
./configure --prefix=/usr
make clean
make
cat dhcpcd > $PKG/sbin/dhcpcd
cat dhcpcd.8 | gzip -9c > $PKG/usr/man/man8/dhcpcd.8.gz
cat << EOF > $PKG/etc/dhcpc/dhcpcd-eth0.exe
#!/bin/sh
echo "(dhcpcd)  IP address changed to \$1" | logger
EOF
chmod 750 $PKG/etc/dhcpc/dhcpcd-eth0.exe
mkdir -p $PKG/usr/doc/dhcpcd-1.3.20-pl0
cp -a pcmcia $PKG/usr/doc/dhcpcd-1.3.20-pl0
cp -a Changes README dhcpcd*.lsm $PKG/usr/doc/dhcpcd-1.3.20-pl0
chown -R root.root $PKG/usr/doc/dhcpcd-1.3.20-pl0

# Build the package:
cd $PKG
tar czvf $TMP/dhcp.tgz .

# Warn of zero-length files:
for file in `find . -type f -print` ; do
 if [ "`filesize $file`" = "0" ]; then
  echo "WARNING: zero length file $file"
 fi
 if [ "`filesize $file`" = "20" ]; then
  echo "WARNING: possible empty gzipped file $file"
 fi
done

# Clean up the extra stuff:
if [ "$1" = "--cleanup" ]; then
 rm -rf $TMP/dhcpcd-1.3.20-pl0
 rm -rf $TMP/dhcp-2.0pl5
 rm -rf $PKG
fi