#!/bin/bash

#####################
# stop the milter if it is already installed
if [ -f /etc/rc.d/init.d/dnsbl ]; then
    /etc/rc.d/init.d/dnsbl stop
    rm -f /etc/rc.d/init.d/dnsbl
fi


#####################
# build the milter
# add compiler flags - suggested by Nigel Horne
g++ -c $CXXFLAGS -pthread dnsbl.cpp scanner.cpp context.cpp tokenizer.cpp
if [ $? -ne 0 ]; then
    echo "compiler errors"
    exit
fi
g++ -o dnsbl dnsbl.o scanner.o context.o tokenizer.o /usr/lib/libresolv.a -lmilter -pthread
if [ $? -ne 0 ]; then
    echo "linker errors"
    exit
fi


#####################
# ensure the user is created
/usr/bin/getent passwd dnsbl || /usr/sbin/useradd -r -d /etc/dnsbl -M -c "dnsbl pseudo-user" -s /sbin/nologin dnsbl
# install the milter
DST=/etc/dnsbl
mkdir -p $DST
if [ -f /var/dnsbl/dnsbl.conf ]; then
    # move the conf files to the new location
    mv /var/dnsbl/*conf $DST
    rm /var/dnsbl/dnsbl # remove the old binary
    rmdir /var/dnsbl
fi
CONF=$DST/dnsbl.conf
if [ -f $CONF ]; then
    grep '^context' $CONF >/dev/null
    if [ $? -eq 1 ]; then
        # config file exists, but it is for the older version
        # preserve it and start over
        suf=4.old
        for i in dnsbl hosts-ignore html-tags tld; do
            j=$DST/$i.conf
            if [ -f $j ]; then
                mv -f $j $j.$suf
            fi
        done
    fi
fi
if [ ! -f $CONF ]; then
    cp dnsbl.conf        $DST
    cp hosts-ignore.conf $DST
    cp html-tags.conf    $DST
    cp tld.conf          $DST
fi
if [ ! -f $DST/hosts-ignore.conf ]; then
    cp hosts-ignore.conf $DST
fi
if [ ! -f $DST/html-tags.conf ]; then
    cp html-tags.conf $DST
fi
if [ ! -f $DST/tld.conf ]; then
    cp tld.conf $DST
fi

# make the directory for the socket
mkdir -p          /var/run/dnsbl
chown dnsbl:dnsbl /var/run/dnsbl
chmod 700         /var/run/dnsbl

# install the binaries
mv -f dnsbl /usr/sbin/dnsbl
cp dnsbl.rc /etc/rc.d/init.d/dnsbl
chmod 755 /etc/rc.d/init.d/dnsbl
/sbin/chkconfig --add dnsbl
/sbin/chkconfig --level 2345 dnsbl on
/etc/rc.d/init.d/dnsbl start
