#!/bin/sh

INSTALL_DIR=`pwd`
SOFTWARE=netqmail
VERSION=1.05

function cleanupandexit {
  echo "Installation failed.  Look above for errors."
  cd $INSTALL_DIR
  rm -rf ${SOFTWARE}-${VERSION}
  exit 1
}

tar zxf ${SOFTWARE}-${VERSION}.tar.gz || cleanupandexit
cd $INSTALL_DIR/${SOFTWARE}-${VERSION} || cleanupandexit
./collate.sh || cleanupandexit
cd $INSTALL_DIR/${SOFTWARE}-${VERSION}/${SOFTWARE}-${VERSION} || cleanupandexit

mkdir /opt/qmail || cleanupandexit
ln -s /opt/qmail /var/qmail || cleanupandexit

groupadd -g 300 nofiles
useradd -u 300 -g nofiles -d /var/qmail/alias alias
useradd -u 301 -g nofiles -d /var/qmail qmaild
useradd -u 302 -g nofiles -d /var/qmail qmaill
useradd -u 303 -g nofiles -d /var/qmail qmailp
groupadd -g 301 qmail
useradd -u 304 -g qmail -d /var/qmail qmailq
useradd -u 305 -g qmail -d /var/qmail qmailr
useradd -u 306 -g qmail -d /var/qmail qmails

make setup check || cleanupandexit

# host=$(./dnsfq `./hostname` 2>/dev/null) || host=`echo -en "Unable to determine fully qualified hostname.\nHostname: " > /dev/stderr; read host; echo $host`

host=$(./dnsfq `./hostname` 2>/dev/null) || host=`host=$(./hostname); echo -en "Unable to determine fully qualified hostname.  Defaulting to local hostname:\n$host\nPress Enter to continue..." > /dev/stderr; read; echo $host`

./config-fast $host || cleanupandexit
(cd ~alias; touch .qmail-postmaster .qmail-mailer-daemon .qmail-root) || cleanupandexit
chmod 644 ~alias/.qmail* || cleanupandexit

cp $INSTALL_DIR/misc/rc /var/qmail/ || cleanupandexit
chgrp qmail /var/qmail/rc || cleanupandexit

# turn on SPF checking
echo 3 > /var/qmail/control/spfbehavior

# turn on mfcheck
echo 1 > /var/qmail/control/mfcheck

cd $INSTALL_DIR/../djbdns/
./install.sh || cleanupandexit

cd $INSTALL_DIR
./install-fake-mta.sh || cleanupandexit

cd $INSTALL_DIR
./install-qmail-conf.sh || cleanupandexit
./qmail-conf-qmail.sh || cleanupandexit
./qmail-conf-smtpd.sh || cleanupandexit

cd $INSTALL_DIR/../../inter7/autorespond
./install.sh || cleanupandexit
cd $INSTALL_DIR/../../inter7/vpopmail
./install.sh || cleanupandexit

cd $INSTALL_DIR/${SOFTWARE}-${VERSION}/${SOFTWARE}-${VERSION}
bunzip2 -cd  ../../patches/qmail-toaster-contegix-0.8.1.patch.bz2 | patch -p0 || cleanupandexit

# Red Hat Kerberos Issue
if test -f /etc/redhat-release; then
  echo "Fixing Red Hat Kerberos Issue"
  sed -e 's/^\(cc.*\)$/\1 -I\/usr\/kerberos\/include/' -i conf-cc
fi

svc -d /service/qmail || cleanupandexit
svc -d /service/smtpd || cleanupandexit

make || cleanupandexit
make setup check || cleanupandexit
make cert || cleanupandexit
make tmprsadh || cleanupandexit
echo ""
echo "Verify the contents of the files in /var/qmail/control at this time"
echo ""
echo "Run install-fake-mta.sh if you want to replace your Sendmail with QMail's"
echo ""
echo "Run install-qmail-conf.sh and the applicable qmail-conf-xxxxx.sh scripts"
echo "to set up the Daemontools services under /service"
echo ""
echo "QMail Installation Complete."


