#!/bin/sh
PKGNAM=dhcp
VERSION=3.0.6
BUILD=${BUILD:-1}

. /etc/pkghelpers

pkghelpers_env

rm -rf $PKG
mkdir -p $PKG

cd $TMP
rm -rf dhcp-$VERSION
tar xzvf $CWD/dhcp-$VERSION.tar.gz
cd dhcp-$VERSION || exit 1

# As we want network manager support, we want a working
# dhclient - thanks gentoo
for patch in $CWD/dhclient-patches/*.patch.gz; do
	echo "Applying $patch..."
	# -p1 or -p0?
	if ! zcat $patch | head -n 1 | cut -f1 -d/ | grep -q dhcp-3; then
		zcat $patch | patch -p0 --verbose || exit 1
	else
		zcat $patch | patch -p1 --verbose || exit 1
	fi
done

./configure
make DEBUG="$SLKCFLAGS" || exit 1
make DEBUG="$SLKCFLAGS" install DESTDIR=$PKG
mkdir -p $PKG/var/state/dhcp
touch $PKG/var/state/dhcp/dhcpd.leases.new
rm -rf $PKG/usr/local
mkdir -p $PKG/usr/doc/dhcp-$VERSION
cp -a \
  LICENSE README RELNOTES \
  $PKG/usr/doc/dhcp-$VERSION
mkdir -p $PKG/usr/doc/dhcp-$VERSION/examples
cp -a client/dhclient.conf server/dhcpd.conf \
  $PKG/usr/doc/dhcp-$VERSION/examples
chown -R root:root $PKG/usr/doc/dhcp-$VERSION
cat << EOF > $PKG/etc/dhcpd.conf.new
# dhcpd.conf
#
# Configuration file for ISC dhcpd (see 'man dhcpd.conf')
#
EOF
cat << EOF > $PKG/etc/dhclient.conf.new
# dhclient.conf
#
# Configuration file for ISC dhclient (see 'man dhclient.conf')
#
EOF
cat client/scripts/linux > $PKG/sbin/dhclient-script
chmod 700 $PKG/sbin/dhclient-script

cd $PKG
pkghelpers_fixup
mkdir -p install
cat $CWD/slack-desc > install/slack-desc
cat << EOF > 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/dhcpd.conf.new
config etc/dhclient.conf.new
config var/state/dhcp/dhcpd.leases.new
rm -f var/state/dhcp/dhcpd.leases.new
EOF

pkghelpers_makepkg