#!/bin/sh

set -e

pomng_extensions="base condition ROUTE addrtype IPMARK string TCPLAG XOR policy"

iptables="iptables-1.2.11"
pomng="patch-o-matic-ng-20040621"
kernel="linux-2.4.26"
ipset="ipset"

dba=$(dpkg-architecture -qDEB_BUILD_ARCH)

pwd="$(pwd)"
build="${pwd}/debian/build"
doc="${build}/doc"
stamp="${build}/stamp"
patches="${pwd}/patches"
upstream="${pwd}/upstream"
arch_patches="${patches}/${dba}"
iptables_profectio="${build}/${iptables}"
kernel_profectio="${build}/${kernel}"
pomng_profectio="${build}/${pomng}"

unpack() {
  for tarball in "$@"; do
    tarball="${tarball}.tar.bz2"
    dinfo "$tarball"
    bunzip2 -dc "${upstream}/${tarball}" | ( cd "$build"; tar xf - )
  done
}

sgml() {
  for sgmldoc in "$@"; do
    sgmldoc="${sgmldoc}-HOWTO.sgml"
    dinfo "$sgmldoc"
    sgml2html "${upstream}/${sgmldoc}" >/dev/null 2>&1
  done
}

dinfo () {
  echo "${0} - ${*}"
}

test -f "${stamp}/prep" && {
  echo already prepared.
  exit 0
}

# package build paths
dinfo "installing source symlinks."
install -d "$doc" "$stamp"
(cd "$build"; ln -sf "$iptables" iptables_profectio; ln -sf "$kernel" kernel_profectio)

# unpack upstream tarballs
dinfo "preparing upstream source..."
unpack "$kernel"
unpack "$iptables"
unpack "$pomng"
ln -s "${build}/${ipset}" "$iptables_profectio/ipset"

unpack "$ipset"
> ${build}/ipset/Makefile

# patch-o-matic-ng
dinfo "applying patch-o-matic-ng..."

for i in $pomng_extensions; do
  (cd "$pomng_profectio";
    ./runme  --batch -kernel-path $kernel_profectio \
      --iptables-path $iptables_profectio $i)
done

# do man pages here, after pomng, so local patches can be applied
dinfo "buidling man pages..."
(cd "$iptables_profectio"; make iptables.8 ip6tables.8)

# compile upstream changelog
dinfo "assembling changelog..."
rm -f "${doc}/changelog"
for i in $((cd ${upstream}; ls CL???-changes*) | sort -r); do
  dinfo "$i"
  if echo $i | grep -q .txt; then
    cat "${upstream}/${i}" >>  "${doc}/changelog"
  elif echo $i | grep -q .html; then
    html2text -o - "${upstream}/$i" >> "${doc}/changelog"
  fi
done

# process sgml HOWTOS
dinfo "processing sgml documents..."
( cd ${doc}; sgml packet-filtering NAT netfilter-hacking netfilter-extensions )

# local debian patches
dinfo "applying local patches..."
  #fix this mess up or something, please
if test -d "$arch_patches"; then
  patches="$patches/all $arch_patches"
else
  patches="$patches/all"
fi
for patch in $(find $patches -maxdepth 1 -type f -name \*.patch | sort -k 3 -t /); do
  dinfo "${patch##*/patches/}"
  patch -p1 -s -d "$build" < "$patch"
done

touch "${stamp}/prep"

dinfo "done."
