#!/bin/sh
# $Id: cyrus-imapd.SlackBuild,v 1.26 2023/12/06 10:27:55 root Exp root $
# Copyright 2004, 2010, 2011, 2017, 2023  Eric Hameleers, Eindhoven, NL
# Inspired by the RPM cyrus-imapd.spec script maintained by Simon Matter.
# All rights reserved.
#
#   Permission to use, copy, modify, and distribute this software for
#   any purpose with or without fee is hereby granted, provided that
#   the above copyright notice and this permission notice appear in all
#   copies.
#
#   THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
#   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
#   IN NO EVENT SHALL THE AUTHORS AND COPYRIGHT HOLDERS AND THEIR
#   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
#   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
#   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
#   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
#   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
#   SUCH DAMAGE.
# -----------------------------------------------------------------------------
#
# Slackware SlackBuild script 
# ===========================
# By:         Eric Hameleers <alien@slackware.com>
# For:        cyrus-imapd
# Descr:      high-performance IMAP mailserver
#             This SlackBuild derived from the RPM spec file and sources,
#             found at http://www.invoca.ch/pub/packages/cyrus-imapd/
# URL:        http://www.cyrusimap.org/
# Needs:      
# Changelog:  
# 2.2.8-1:    07/oct/2004 by Eric Hameleers
#             * First release
# 2.2.8-2:    24/oct/2004 by Eric Hameleers
#             * Missing $BDB_INC includes in the  Perl Makefiles for cyradm
#               and sieveshell (leading to Berkeley db4 not being found during
#               compilation and runtime errors like "undefined symbol:
#               db_version")
# 2.2.8-3:   25/oct/2004 by Eric Hameleers
#            * Another try to fix the "undefined symbol: db_version" error for
#              cyradm and sieveshell (put $BDB_INC before any other include_dirs
#              and add "-ldb-4.2" too)
# 2.2.8-4:    01/nov/2004 by Eric Hameleers
#             * Add a README.PKG to the doc directory. IT is derived from the
#               Invoca "README.RPM" and contains a "quick'n'dirty setup guide".
# 2.3.16-1:   01/nov/2010 by Eric Hameleers <alien@slackware.com>
#             * Updated for Slackware 13.1.
# 2.4.10-1:   10/aug/2011 by Eric Hameleers <alien@slackware.com>
#             * Updated - note that proc and lock directories are now created
#               in /dev/shm for performance reasons, so you have to change the
#               mount options in fstab for /dev/shm from 'defaults' to;
#               'defaults,nodev,nosuid,mode=1777'
# 2.4.19-1:   04/aug/2017 by Eric Hameleers <alien@slackware.com>
#             * Updated.
# 2.4.22-1:   05/dec/2023 by Eric Hameleers <alien@slackware.com>
#             * Updated. Switch from bdb to sqlite (cyrus-imapd 3.0 drops
#               bdb suupport). The database switch needs careful migration, see
#               https://www.cyrusimap.org/3.0/imap/download/upgrade.html
# 
# Run 'sh cyrus-imapd.SlackBuild' to build a Slackware package.
# The package (.txz) and .txt file as well as build logs are created in /tmp .
# Install it using 'installpkg'. 
#
# -----------------------------------------------------------------------------

# Set initial variables:

PRGNAM=cyrus-imapd
VERSION=${VERSION:-2.4.22}
MINOR=${MINOR:-2.el8}
BUILD=${BUILD:-1}
unset NUMJOBS
unset MAKEFLAGS
TAG=${TAG:-alien}

# Where do we look for sources?
SRCDIR=$(cd $(dirname $0); pwd)

# What docs to add:
DOCS="COPYRIGHT README doc/*"

# Where is perl?
PERL=$(which perl)

# Place to build (TMP) package (PKG) and output (OUTPUT) the program:
TMP=${TMP:-/tmp/build}
PKG=$TMP/package-$PRGNAM
OUTPUT=${OUTPUT:-/tmp}

# Downloadable RPM:
SOURCE[0]="$SRCDIR/${PRGNAM}-${VERSION}-${MINOR}.src.rpm"
SRCURL[0]="http://www.invoca.ch/pub/packages/${PRGNAM}/RPMS/ils-5/SRPMS/${PRGNAM}-${VERSION}-${MINOR}.src.rpm"

# Files inside the RPM:
Source3=cyrus-deliver-wrapper.c
Source4=cyrus-user-procmailrc.template
Source5=cyrus-imapd.logrotate
Source6=cyrus-imapd.imap-2.3.x-conf
Source9=skiplist.py
Source10=cyrus-imapd-skipfix.sh
Source11=cyrus-imapd.init
Source12=cyrus-imapd.sysconfig
Source13=cyrus-imapd.cvt_cyrusdb_all
Source14=cyrus-imapd.magic
Source15=imapcreate.pl
Source16=cyrus_ldap_quota.pl
Source17=batchreconstruct
Source18=bsd2cyrus
Source19=cpmsg
Source20=folderxfer
Source21=inboxfer
Source22=cyrus_sharedbackup-0.1.tar.gz
Source23=cyrus-imapd-README.RPM
Source24=cyrus-imapd-README.HOWTO-recover-mailboxes.db
Source25=cyrus-imapd.cron-daily
Source26=cyrus-procmailrc
Source27=cyrus-imapd-procmail+cyrus.mc
Source28=cyrus-imapd.rpm_set_permissions
Source29=cyrus-imapd-sendmail-8.12.9-cyrusv2.m4
Source30=cyrus-imapd-README.contrib
Source31=cyrus-imapd-README.groupcache
Source32=cyrus-imapd.upd_groupcache
Source33=cyrus-imapd-README.skiplist_recovery
Source34=cyrus-imapd-README.performance-tips
Source35=cyrus-imapd-README.notify_sms
Source36=cyrus-imapd.archive_mboxlist
Source37=cyrus-imapd.run_all_instances
Source38=cyrus-imapd.add_instance
Source39=cyrus-imapd.del_instance
Source40=cyrus-imapd-README.multi-instance
Source41=rfc4314.txt

Patch0=cyrus-imapd-2.2.12-no_transfig.patch
Patch1=cyrus-imapd-2.4.20-notify_sms.patch
Patch2=cyrus-imapd-2.1.16-getrlimit.patch
Patch3=cyrus-imapd-2.4.11beta1-flock.patch
Patch4=cyrus-imapd-2.3.11-groupcache.patch
Patch5=cyrus-imapd-2.4.17-config_defaults.patch
Patch6=cyrus-imapd-2.4.17-volatile.patch
Patch7=cyrus-imapd-2.3.11-mkimap.patch
Patch8=cyrus-imapd-2.4.14-authid_normalize.patch
Patch9=cyrus-imapd-2.4.10-appenddomain.patch
Patch10=cyrus-imapd-2.4.4-statuscache_verbosity.patch
Patch11=cyrus-imapd-2.3.12-skiplist_verbosity.patch
Patch12=sieve-min.diff
Patch13=cyrus-imapd-2.4.10-user_deny_verbosity.patch
Patch14=cyrus-imapd-2.3.16-sieve_port.patch
Patch15=cyrus-imapd-2.4.6-expire_config.patch
Patch16=cyrus-imapd-2.3.7-nobarenewlinescheck.patch
Patch17=cyrus-imapd-2.4.12-debugopt.patch
Patch18=cyrus-imapd-2.4.18-statuscache_volatile.patch
Patch19=cyrus-imapd-2.4.17-tlscache_volatile.patch
Patch20=cyrus-imapd-2.4.19-cyrus_mkdir.patch
Patch21=cyrus-imapd-2.4.20-lmtptarget.patch
Patch90=cyrus-imapd-2.4.19-autocreate-0.10-0.patch
Patch91=cyrus-imapd-2.4.18-autosieve-0.6.0.patch
Patch92=cyrus-imapd-2.4.20-autosieve-CVE-2019-19783.patch

# patches >= 100 are / will be fixed in SCM
Patch100=c532115a11eb1742ff53ed821685d8d975e2af0f.patch
Patch101=7c3156bb511b6b84413eead1ffd99bd818bb9b71.patch
Patch102=d415da7ae571c3854550564a1764e763cc83c921.patch
Patch103=f63695609c88a3f76129499bb49fb82e8155fb32.patch
Patch104=833c22bd7de5bbb591c2cb3705c9983b6d2b1fee.patch

# patches >= 1000 are for private build tools
Patch1000=m4-1.4.18-glibc-change-work-around.patch

##
## --- with a little luck, you won't have to edit below this point --- ##
##

# Automatically determine the architecture we're building on:
if [ -z "$ARCH" ]; then
  case "$(uname -m)" in
    i?86) ARCH=i586 ;;
    arm*) readelf /usr/bin/file -A | egrep -q "Tag_CPU.*[4,5]" && ARCH=arm || ARCH=armv7hl ;;
    # Unless $ARCH is already set, use uname -m for all other archs:
    *) ARCH=$(uname -m) ;;
  esac
  export ARCH
fi

case "$ARCH" in
  i?86)      SLKCFLAGS="-O2 -march=${ARCH} -mtune=i686"
             SLKLDFLAGS=""; LIBDIRSUFFIX=""
             ;;
  x86_64)    SLKCFLAGS="-O2 -fPIC"
             SLKLDFLAGS="-L/usr/lib64"; LIBDIRSUFFIX="64"
             ;;
  *)         SLKCFLAGS="-O2"
             SLKLDFLAGS=""; LIBDIRSUFFIX=""
             ;;
esac

case "$ARCH" in
    arm*)    TARGET=$ARCH-slackware-linux-gnueabi ;;
    *)       TARGET=$ARCH-slackware-linux ;;
esac

# Exit the script on errors:
set -e
trap 'echo "$0 FAILED at line ${LINENO}" | tee $OUTPUT/error-${PRGNAM}.log' ERR
# Catch unitialized variables:
set -u
P1=${1:-1}

# Save old umask and set to 0022:
_UMASK_=$(umask)
umask 0022

# Create working directories:
mkdir -p $OUTPUT          # place for the package to be saved
mkdir -p $TMP/tmp-$PRGNAM # location to build the source
mkdir -p $PKG             # place for the package to be built
rm -rf $PKG/*             # always erase old package's contents
rm -rf $TMP/tmp-$PRGNAM/* # remove the remnants of previous build
rm -rf $OUTPUT/{configure,make,install,error,makepkg}-$PRGNAM.log
                          # remove old log files

# Source file availability:
for (( i = 0; i < ${#SOURCE[*]}; i++ )) ; do
  if ! [ -f ${SOURCE[$i]} ]; then
    echo "Source '$(basename ${SOURCE[$i]})' not available yet..."
    # Check if the $SRCDIR is writable at all - if not, download to $OUTPUT
    [ -w "$SRCDIR" ] || SOURCE[$i]="$OUTPUT/$(basename ${SOURCE[$i]})"
    if [ -f ${SOURCE[$i]} ]; then echo "Ah, found it!"; continue; fi
    if ! [ "x${SRCURL[$i]}" == "x" ]; then
      echo "Will download file to $(dirname $SOURCE[$i])"
      wget --no-check-certificate -nv -T 20 -O "${SOURCE[$i]}" "${SRCURL[$i]}" || true
      if [ $? -ne 0 -o ! -s "${SOURCE[$i]}" ]; then
        echo "Fail to download '$(basename ${SOURCE[$i]})'. Aborting the build."
        mv -f "${SOURCE[$i]}" "${SOURCE[$i]}".FAIL
        exit 1
      fi
    else
      echo "File '$(basename ${SOURCE[$i]})' not available. Aborting the build."
      exit 1
    fi
  fi
done

if [ "$P1" == "--download" ]; then
  echo "Download complete."
  exit 0
fi

# --- PACKAGE BUILDING ---

echo "++"
echo "|| $PRGNAM-$VERSION"
echo "++"

# Configurable parameters for the build:
CYRUID=76
CYRUSR=cyrus
CYRGRP=mail
CYRVAR=/var/lib/imap
CYRSPOOL=/var/spool/imap
CYRSYSLOG=MAIL
CYREXEC=/usr/lib${LIBDIRSUFFIX}/${PRGNAM}
CYRCONFDIR=master/conf
CYRCONTRIB=/usr/doc/${PRGNAM}-${VERSION}/contrib
CYRCONFFILE=${CYRCONFDIR}/prefork.conf

cd $TMP/tmp-$PRGNAM
echo "Extracting the source archive(s) for $PRGNAM..."
rpm2cpio ${SOURCE[0]} | cpio -vimd
tar xvf ${PRGNAM}-${VERSION}.tar.gz
cd ${PRGNAM}-${VERSION}

# Preserve dist options:
cp -a lib/imapoptions lib/imapoptions.dist

# Fix a compilation error caused by newer GCC than Red Hat use:
sed -e 's/gettid/_gettid/g' -i lib/cyrusdb_berkeley.c

# Apply all Invoca patches:
touch $OUTPUT/patch-${PRGNAM}.log
(
  # apply SCM patches first, some other patches my depend on them
  cat ../$Patch100| patch --verbose -p1 -b -z .c532115a11eb1742ff53ed821685d8d975e2af0f
  cat ../$Patch101| patch --verbose -p1 -b -z .7c3156bb511b6b84413eead1ffd99bd818bb9b71
  cat ../$Patch102| patch --verbose -p1 -b -z .d415da7ae571c3854550564a1764e763cc83c921
  cat ../$Patch103| patch --verbose -p1 -b -z .f63695609c88a3f76129499bb49fb82e8155fb32
  cat ../$Patch104| patch --verbose -p1 -b -z .833c22bd7de5bbb591c2cb3705c9983b6d2b1fee

  cat ../$Patch0  | patch --verbose -p1 -b -z .no_transfig
  cat ../$Patch1  | patch --verbose -p1 -b -z .notify_sms
  cat ../$Patch2  | patch --verbose -p1 -b -z .getrlimit
  cat ../$Patch3  | patch --verbose -p1 -b -z .flock
  cat ../$Patch4  | patch --verbose -p1 -b -z .groupcache
  cat ../$Patch5  | patch --verbose -p1 -b -z .config_defaults
  cat ../$Patch6  | patch --verbose -p1 -b -z .volatile
  cat ../$Patch7  | patch --verbose -p1
  cat ../$Patch8  | patch --verbose -p1 -b -z .authid_normalize
  cat ../$Patch9  | patch --verbose -p1 -b -z .appenddomain
  cat ../$Patch10 | patch --verbose -p1 -b -z .statuscache_verbosity
  cat ../$Patch11 | patch --verbose -p1 -b -z .skiplist_verbosity
  cat ../$Patch12 | patch --verbose -p1 -b -z .sieve-min
  cat ../$Patch13 | patch --verbose -p1 -b -z .user_deny_verbosity
  cat ../$Patch14 | patch --verbose -p1 -b -z .sieve_port
  cat ../$Patch15 | patch --verbose -p1 -b -z .expire_config
  cat ../$Patch16 | patch --verbose -p1 -b -z .nobarenewlinescheck
  cat ../$Patch17 | patch --verbose -p1 -b -z .debugopt
  cat ../$Patch18 | patch --verbose -p1 -b -z .statuscache_volatile
  cat ../$Patch19 | patch --verbose -p1 -b -z .tlscache_volatile
  cat ../$Patch20 | patch --verbose -p1 -b -z .cyrus_mkdir
  cat ../$Patch21 | patch --verbose -p1 -b -z .lmtptarget
  cat ../$Patch90 | patch --verbose -p1 -b -z .autocreate
  cat ../$Patch91 | patch --verbose -p1 -b -z .autosieve
  cat ../$Patch92 | patch --verbose -p1 -b -z .autosieve-CVE-2019-19783
) 2>&1 | tee $OUTPUT/patch-${PRGNAM}.log

# preserve timestamp of the files for different builds
find . -type f -mtime -1 -exec touch -r ${SOURCE[0]} {} \;

# Apply sane file permmissions:
chown -R root:root .
chmod -R u+w,go+r-w,a+rX-st .

echo Building ...

# The patches have touched the autoconf files:
( aclocal -I cmulocal
  autoheader
  autoreconf -vif
 ) 2>&1 | tee $OUTPUT/autoreconf-${PRGNAM}.log

export LDFLAGS="$SLKLDFLAGS"
export CPPFLAGS="-I/usr/include/et"
export CFLAGS="$SLKCFLAGS"
export CCDLFLAGS="-rdynamic"
./configure \
  --prefix=/usr \
  --libdir=/usr/lib${LIBDIRSUFFIX} \
  --mandir=/usr/man \
  --docdir=/usr/doc/$PRGNAM-$VERSION \
  --localstatedir=/var \
  --sysconfdir=/etc \
  --enable-netscapehack \
  --enable-listext \
  --enable-idled \
  --enable-murder \
  --enable-replication \
  --enable-nntp \
  --without-libwrap \
  --without-snmp \
  --with-auth=unix \
  --with-ldap \
  --with-perl=${PERL} \
  --with-cyrus-prefix=${CYREXEC} \
  --with-service-path=${CYREXEC} \
  --with-sqlite \
  --with-extraident="Slackware-Invoca-${VERSION}-${BUILD}" \
  --with-syslogfacility=${CYRSYSLOG} \
  --disable-static \
  --program-prefix= \
  --program-suffix= \
  --build=$TARGET \
  2>&1 | tee $OUTPUT/configure-${PRGNAM}.log

touch $OUTPUT/make-${PRGNAM}.log
make clean # required to prevent failure, but why?!?
make -C man -f Makefile.dist 2>&1 | tee -a $OUTPUT/make-${PRGNAM}.log
make -C doc -f Makefile.dist 2>&1 | tee -a $OUTPUT/make-${PRGNAM}.log
make all 2>&1 | tee -a $OUTPUT/make-${PRGNAM}.log
make -C notifyd notifytest 2>&1 | tee -a $OUTPUT/make-${PRGNAM}.log
make -C imtest 2>&1 | tee -a $OUTPUT/make-${PRGNAM}.log
cc $CFLAGS -DLIBEXECDIR=\"${CYREXEC}\" -Wall -o deliver-wrapper ../${Source3}

# Modify docs master --> cyrus-master
( cd man &&
  sed -i -e "s#master(8)#cyrus-master(8)#" $(ls *5 *8)
)
( cd doc &&
  sed -i -e "s#master#cyrus-master#g" man.html
)
( cd doc/man &&
  sed -i -e "s#master(8)#cyrus-master(8)#g" $(ls *html)
)

# Modify path in perl scripts
sed -i -e "s#/usr/local/bin/perl#${PERL}#" $(find . -type f -name "*.pl")

# Fix permissions on perl programs
find . -type f -name "*.pl" -exec chmod 0755 {} \;

# Add perl documentation:
cp perl/imap/README doc/README.perl
cp perl/imap/Changes doc/Changes.perl
cp -a perl/imap/examples doc/perl_examples

# Cleanup of doc dir:
find doc perl -name CVS -type d -depth -exec rm -rf {} \;
find doc perl -name .cvsignore -type f -exec rm -rf {} \;
find doc -name "*~" -type f -exec rm -f {} \;
find doc -name "*.html.*" -type f -exec rm -f {} \;
rm -f doc/Makefile.dist*
rm -f doc/text/htmlstrip.c

# Install 3rd party documentation and utilities:
install -m 0644 -p ../${Source24}  doc/README.HOWTO-recover-mailboxes.db
install -m 0644 -p ../${Source31}  doc/README.groupcache
install -m 0644 -p ../${Source33}  doc/README.skiplist_recovery
install -m 0644 -p ../${Source34}  doc/README.performance-tips
install -m 0644 -p ../${Source35}  doc/README.notify_sms
install -m 0644 -p ../${Source40}  doc/README.multi-instance
install -d doc/m4
install -m 0644 -p ../${Source26}  doc/m4/cyrus-procmailrc
install -m 0644 -p ../${Source4}   doc/m4/cyrus-user-procmailrc.template
install -m 0644 -p ../${Source27}  doc/m4/${PRGNAM}-procmail+cyrus.mc
install -m 0644 -p ../${Source29}  doc/m4/${PRGNAM}-sendmail-8.12.9-cyrusv2.m4
install -d doc/rfc
install -m 0644 -p ../${Source41}  doc/rfc/rfc4314.txt

# A README for Slackware, derived from the one written by Simon Matter:
install -m 0644 -p ${SRCDIR}/${PRGNAM}-README.PKG     doc/README.PKG

# Modify lmtp socket path in .conf files:
sed -i -e "s#/var/imap/#${CYRVAR}/#" ${CYRCONFDIR}/*.conf doc/cyrusv2.mc doc/m4/${PRGNAM}-sendmail-8.12.9-cyrusv2.m4

# Enable idled in .conf files to prevent error messages:
sed -i -e "s/#  idled/  idled/" ${CYRCONFDIR}/*.conf

# Install into the package directory:
touch $OUTPUT/install-${PRGNAM}.log
cd perl/imap
perl Makefile.PL DESTDIR=$PKG PREFIX=/usr \
  INSTALLVENDORMAN1DIR=/usr/man/man1 INSTALLVENDORMAN3DIR=/usr/man/man3 INSTALLDIRS=vendor \
  2>&1 | tee -a $OUTPUT/install-${PRGNAM}.log
cd -
cd perl/sieve/managesieve
perl Makefile.PL DESTDIR=$PKG PREFIX=/usr \
  INSTALLVENDORMAN1DIR=/usr/man/man1 INSTALLVENDORMAN3DIR=/usr/man/man3 INSTALLDIRS=vendor \
  2>&1 | tee -a $OUTPUT/install-${PRGNAM}.log
cd - 
make DESTDIR=$PKG PREFIX=/usr mandir=/usr/man install \
  2>&1 | tee -a $OUTPUT/install-${PRGNAM}.log
make -C man DESTDIR=$PKG PREFIX=/usr mandir=/usr/man install \
  2>&1 | tee -a $OUTPUT/install-${PRGNAM}.log

# Some administrative utilities:
install -m 0755 -p deliver-wrapper    $PKG/${CYREXEC}
install -m 0755 -p imtest/imtest      $PKG/usr/bin
install -m 0755 -p notifyd/notifytest $PKG/usr/bin
install -m 0755 -p perl/imap/cyradm   $PKG/usr/bin

# Install tools:
rm -f tools/*.orig
for tool in tools/*; do
  test -f ${tool} && install -m 0755 -p ${tool} ${PKG}${CYREXEC}/
done

# Create required directories:
install -d \
  ${PKG}/etc/{rc.d,logrotate.d,cron.daily} \
  ${PKG}/etc/ssl/certs \
  ${PKG}/usr/share/${PRGNAM}/slack \
  ${PKG}/var/log/imap \
  ${PKG}${CYREXEC}/slack \
  ${PKG}${CYRSPOOL}/stage. \
  ${PKG}${CYRVAR}/{user,quota,proc,log,msg,socket,db,db.backup1,db.backup2,sieve,sync,md5,sha1,slack,backup,meta,volatile} \
  ${PKG}${CYRVAR}/ptclient \
  ${PKG}${CYRCONTRIB}

# Install additional files:
install -m 0755 -p ../${Source13}  ${PKG}${CYREXEC}/slack/cvt_cyrusdb_all
install -m 0755 -p ../${Source32}  ${PKG}${CYREXEC}/slack/upd_groupcache
install -m 0755 -p ../${Source28}  ${PKG}${CYREXEC}/slack/slack_set_permissions
install -m 0755 -p ../${Source36}  ${PKG}${CYREXEC}/slack/archive_mboxlist
install -m 0755 -p ../${Source37}  ${PKG}${CYREXEC}/slack/run_all_instances
install -m 0755 -p ../${Source38}  ${PKG}${CYREXEC}/slack/add_instance
install -m 0755 -p ../${Source39}  ${PKG}${CYREXEC}/slack/del_instance
cd ${PKG}${CYREXEC}
  for script in slack/*; do
    ln -sf $script .
  done
cd -
install -m 0644 -p ../${Source14}  ${PKG}/usr/share/${PRGNAM}/slack/magic
install -m 0644 -p ../${Source15}  $PKG/${CYRCONTRIB}/imapcreate
install -m 0644 -p ../${Source16}  $PKG/${CYRCONTRIB}/cyrus_ldap_quota
install -m 0644 -p ../${Source17}  $PKG/${CYRCONTRIB}/batchreconstruct
install -m 0644 -p ../${Source18}  $PKG/${CYRCONTRIB}/bsd2cyrus
install -m 0644 -p ../${Source19}  $PKG/${CYRCONTRIB}/cpmsg
install -m 0644 -p ../${Source20}  $PKG/${CYRCONTRIB}/folderxfer
install -m 0644 -p ../${Source21}  $PKG/${CYRCONTRIB}/inboxfer
install -m 0644 -p ../${Source22}  $PKG/${CYRCONTRIB}/
install -m 0644 -p ../${Source30}  $PKG/${CYRCONTRIB}/README
install -m 0644 -p ../${Source9}   $PKG/${CYRCONTRIB}/
install -m 0644 -p ../${Source10}  $PKG/${CYRCONTRIB}/skipfix.sh

# Fix permissions
find ${PKG}/usr/lib${LIBDIRSUFFIX}/perl5/ -type f -name "*.so" -exec chmod 0755 {} \;
chmod 0644 perl/imap/examples/*

# Install config files:
install -m 0644 -p ${CYRCONFFILE}    ${PKG}/etc/cyrus.conf
install -m 0644 -p ../${Source6}     ${PKG}/etc/imapd.conf
install -m 0644 -p ../${Source12}    ${PKG}/etc/rc.d/rc.${PRGNAM}.conf
install -m 0644 -p ../${Source5}     ${PKG}/etc/logrotate.d/${PRGNAM}
install -m 0755 -p ../${Source25}    ${PKG}/etc/cron.daily/${PRGNAM}

# Install the Slackware rc script:
install -m 0755 -p $SRCDIR/rc.${PRGNAM} ${PKG}/etc/rc.d/rc.${PRGNAM}
sed -i -e "s#LIB#/usr/lib${LIBDIRSUFFIX}#g" $PKG/etc/rc.d/rc.${PRGNAM}

# Install templates:
install -d doc/conf
install -m 0644 -p ${CYRCONFDIR}/*.conf doc/conf/

# Generate imapd.conf.*
cp -a lib/imapoptions lib/imapoptions.default
for config in dist default; do
  { grep "^\{\ " lib/imapoptions.${config} | \
    cut -d"," -f1,2 | \
    sed \
      -e "s@^{\ \"@@g" \
      -e "s@\",\ @: @" \
      -e "s@\ NULL@@" \
      -e "s@\ \"@ @" \
      -e "s@\ \"@@" \
      -e "s@\"\$@@" | \
    sort
  } >  ${PKG}/usr/share/${PRGNAM}/slack/imapd.conf.${config}
done

# Generate db.cfg
{ grep "^\{\ " lib/imapoptions | \
  grep "_db" | \
  sed \
    -e "s@^{\ \"@@g" \
    -e "s@\",\ @=@" \
    -e "s@NULL@\"\"@" | \
  cut -d"," -f1 | \
  sort
  echo sieve_version=\"$(grep "^#define\ SIEVE_VERSION\ " sieve/sieve_interface.h | cut -d"\"" -f2 | sed -e "s@\ @_@g")\"
} > ${PKG}/usr/share/${PRGNAM}/slack/db.cfg

# Generate build.cfg
{ echo with_idled=1
  echo with_snmp=0
  echo with_groupcache=1
  echo with_syslogfacility=MAIL
  echo with_mysql=0
  echo with_pgsql=0
  echo with_bdb=0
  echo with_sqlite=1
  echo with_ldap=1
} > ${PKG}/usr/share/${PRGNAM}/slack/build.cfg

# Fix cvt_cyrusdb_all and friends for use with this Slackware package:
sed -i -e \
  "s#rpm#slack#g" -e "s#usr/lib/#usr/lib${LIBDIRSUFFIX}/#g" \
  ${PKG}${CYREXEC}/slack/*

# Change config file so ssl certificates are under /etc rather than /usr/share
sed -i -e 's#/usr/share/ssl/certs/#/etc/ssl/certs/#g' ${PKG}/etc/imapd.conf

# Rename 'master' binary and manpage to avoid clash with postfix
mv -f ${PKG}${CYREXEC}/{master,cyrus-master}
mv -f ${PKG}/usr/man/man8/{master,cyrus-master}.8
mv -f doc/man/{master,cyrus-master}.8.html
sed -i -e 's/master/cyrus-master/g'  ${PKG}/usr/man/man8/cyrus-master.8
sed -i -e 's/cyrus-cyrus/cyrus/g'  ${PKG}/usr/man/man8/cyrus-master.8
sed -i -e 's/Master/Cyrus-master/g'  ${PKG}/usr/man/man8/cyrus-master.8
sed -i -e 's/MASTER/CYRUS-MASTER/g'  ${PKG}/usr/man/man8/cyrus-master.8
sed -i -e 's/master/cyrus-master/g'  doc/man/cyrus-master.8.html
sed -i -e 's/cyrus-cyrus/cyrus/g'  doc/man/cyrus-master.8.html
sed -i -e 's/Master/Cyrus-master/g'  doc/man/cyrus-master.8.html
sed -i -e 's/MASTER/CYRUS-MASTER/g'  doc/man/cyrus-master.8.html

# Rename 'fetchnews' binary and manpage to avoid crash with leafnode:
mv -f ${PKG}${CYREXEC}/{fetchnews,cyrfetchnews}
mv -f ${PKG}/usr/man/man8/{fetchnews,cyrfetchnews}.8
mv -f doc/man/{fetchnews,cyrfetchnews}.8.html
sed -i -e 's/fetchnews/cyrfetchnews/g'  ${PKG}/usr/man/man8/cyrfetchnews.8
sed -i -e 's/Fetchnews/Cyrfetchnews/g'  ${PKG}/usr/man/man8/cyrfetchnews.8
sed -i -e 's/FETCHNEWS/CYRFETCHNEWS/g'  ${PKG}/usr/man/man8/cyrfetchnews.8
sed -i -e 's/fetchnews/cyrfetchnews/g'  doc/man/cyrfetchnews.8.html
sed -i -e 's/Fetchnews/Cyrfetchnews/g'  doc/man/cyrfetchnews.8.html
sed -i -e 's/FETCHNEWS/CYRFETCHNEWS/g'  doc/man/cyrfetchnews.8.html

# Useless and empty on x86_64:
rmdir ${PKG}/usr/lib 2>/dev/null || true

# Remove installed but not packaged files:
rm -f ${PKG}${CYREXEC}/not-mkdep
rm -f ${PKG}${CYREXEC}/config2header*
rm -f ${PKG}${CYREXEC}/config2man

# Use symlinks rather than the installed files:
rm -f ${PKG}${CYREXEC}/proxyd
ln -sf imapd ${PKG}${CYREXEC}/proxyd
rm -f ${PKG}${CYREXEC}/pop3proxyd
ln -sf pop3d ${PKG}${CYREXEC}/pop3proxyd
rm -f ${PKG}${CYREXEC}/lmtpproxyd
ln -sf lmtpd ${PKG}${CYREXEC}/lmtpproxyd

# Remove perl cruft and other left-overs:
find ${PKG} -type f -name "perllocal.pod" -exec rm -f {} \;
find ${PKG} -type f -name ".packlist" -exec rm -f {} \;
find ${PKG} -type f -name "*.bs" -exec rm -f {} \;
rm -f doc/text/Makefile
rm -f ${PKG}/usr/man/man8/syncnews.8*
rm -f doc/man/syncnews.8.html

# Take care of configuration files that should not overwrite
# user-modified content:
mv $PKG/etc/cyrus.conf{,.new}
mv $PKG/etc/imapd.conf{,.new}
mv $PKG/etc/rc.d/rc.${PRGNAM}{,.new}
mv $PKG/etc/rc.d/rc.${PRGNAM}.conf{,.new}
mv $PKG/etc/logrotate.d/${PRGNAM}{,.new}
mv $PKG/etc/cron.daily/${PRGNAM}{,.new}

# Add this to the doinst.sh:
mkdir -p $PKG/install
cat <<EOINS >> $PKG/install/doinst.sh
# Handle the incoming configuration files:
config() {
  for infile in \$1; do
    NEW="\$infile"
    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...
  done
}

# Take care of configuration files that should not overwrite
# user-modified content:
config etc/cyrus.conf.new
config etc/imapd.conf.new
config etc/rc.d/rc.${PRGNAM}.new
config etc/rc.d/rc.${PRGNAM}.conf.new
config etc/logrotate.d/${PRGNAM}.new
config etc/cron.daily/${PRGNAM}.new

# Update rc.local so that ${PRGNAM} will be started on boot
if ! grep -q "rc.${PRGNAM}" etc/rc.d/rc.local ; then
  cat <<-_EOM_ >> etc/rc.d/rc.local
	if [ -x /etc/rc.d/rc.${PRGNAM} ]; then
	  # Start Cyrus IMAP daemon
	  echo "Starting Cyrus IMAP server:  /etc/rc.d/rc.${PRGNAM} start"
	  /etc/rc.d/rc.${PRGNAM} start
	fi
	_EOM_
fi

# Create 'cyrus' user on target host:
chroot . \
getent passwd ${CYRUSR} > /dev/null || \
  /usr/sbin/useradd -c "Cyrus IMAP Server" -d ${CYRVAR} -g ${CYRGRP} \
  -s /bin/bash -u ${CYRUID} -r ${CYRUSR} 2>/dev/null

# Set permissions on the imap directories
chown -R ${CYRUSR}:${CYRGRP} .${CYRVAR}
chmod -R 700 .${CYRVAR}
chmod 750 .${CYRVAR}
chmod 750 .${CYRVAR}/socket

# Allow for symlinked spool directory:
chown -R ${CYRUSR}:${CYRGRP} .${CYRSPOOL}/
chmod -R 700 .${CYRSPOOL}/

chown ${CYRUSR}:${CYRGRP} var/log/imap
chmod 750 var/log/imap

# Force synchronous updates, usually only on ext2 filesystems:
for i in ./${CYRVAR}/{user,quota} ./${CYRSPOOL}
do
  if [ "x$(find $i -maxdepth 0 -printf %%F)" = "xext2" ]; then
    chattr -R +S $i 2> /dev/null
  fi
done

# "ctl_deliver -E" is deprecated, now is "cyr_expire -E"
if grep -q "ctl_deliver *-E" etc/cyrus.conf; then
  sed -i -e "s/ctl_deliver *-E/cyr_expire -E/" etc/cyrus.conf
fi

# Prevent idled related errors to show up:
if grep -q "^#  idled" etc/cyrus.conf; then
  sed -i -e "s/^#  idled/  idled/" etc/cyrus.conf
fi

# Change existing config file so ssl certificates are under /etc :
if grep -q "/usr/share/ssl/certs/" etc/imapd.conf; then
  sed -i -e 's#/usr/share/ssl/certs/#/etc/ssl/certs/#g' etc/imapd.conf
fi

# Create SSL certificates:
if [ ! -f etc/ssl/certs/${PRGNAM}.pem ]; then
  echo "Creating self-signed SSL certificate /etc/ssl/certs/${PRGNAM}.pem."
  umask 077
  # Generate the pem-encoded certificate file for secure connections:
  # -- mind the <TAB>'s in the 'here document'  --
  openssl req -new -x509 -days 3650 -nodes \
    -out etc/ssl/certs/${PRGNAM}.pem \
    -keyout etc/ssl/certs/${PRGNAM}.pem \
  <<-EOT 2>/dev/null
	NL
	Netherlands
	Eindhoven
	Alien Base
	Systems Management
	localhost
	root@localhost
	EOT
  chown root:${CYRGRP} etc/ssl/certs/${PRGNAM}.pem
  chmod 640 etc/ssl/certs/${PRGNAM}.pem
  umask 022
fi

# Add service entries if necessary:
if ! grep -q ^lmtp etc/services; then
  echo -e 'lmtp\t\t24/tcp\t\t# LMTP Mail Delivery' >> etc/services
  echo -e 'lmtp\t\t24/udp\t\t# LMTP Mail Delivery' >> etc/services
fi
if ! grep -q ^nntps etc/services; then
  echo -e 'nntps\t\t563/tcp\t\t# NNTP over SSL' >> etc/services
  echo -e 'nntps\t\t563/udp\t\t# NNTP over SSL' >> etc/services
fi
if ! grep -q ^pop3s etc/services; then
  echo -e 'pop3s\t\t995/tcp\t\t# POP-3 over SSL' >> etc/services
  echo -e 'pop3s\t\t995/udp\t\t# POP-3 over SSL' >> etc/services
fi
if ! grep -q ^imaps etc/services; then
  echo -e 'imaps\t\t993/tcp\t\t# IMAP over SSL' >> etc/services
  echo -e 'imaps\t\t993/udp\t\t# IMAP over SSL' >> etc/services
fi
if ! grep -q ^csync etc/services; then
  echo -e 'csync\t\t2005/tcp\t\t# Cyrus IMAP Replication Daemon' >> etc/services
  echo -e 'csync\t\t2005/udp\t\t# Cyrus IMAP Replication Daemon' >> etc/services
fi
if ! grep -q ^mupdate etc/services; then
  echo -e 'mupdate\t\t3905/tcp\t\t# Mailbox Update (MUPDATE) protocol' >> etc/services
  echo -e 'mupdate\t\t3905/udp\t\t# Mailbox Update (MUPDATE) protocol' >> etc/services
fi
if ! grep -q ^sieve etc/services; then
  echo -e 'sieve\t\t4190/tcp\t\t# ManageSieve Protocol' >> etc/services
fi
if ! grep -q ^fud etc/services; then
  echo -e 'fud\t\t4201/udp\t\t# Cyrus IMAP FUD Daemon' >> etc/services
fi

# Finally, run ldconfig
if [ -f etc/ld.so.conf ]; then
  /sbin/ldconfig  -r . 1>/dev/null 2>/dev/null
fi

EOINS
# End of doinst.sh install script.

# Add documentation:
mkdir -p $PKG/usr/doc/$PRGNAM-$VERSION
cp -a \
  $DOCS \
  $TMP/tmp-$PRGNAM/${PRGNAM}.spec \
  $PKG/usr/doc/$PRGNAM-$VERSION \
  || true
cat $SRCDIR/$(basename $0) > $PKG/usr/doc/$PRGNAM-$VERSION/$PRGNAM.SlackBuild
chown -R root:root $PKG/usr/doc/$PRGNAM-$VERSION
find $PKG/usr/doc -type f -exec chmod 644 {} \;

# Compress the man page(s):
if [ -d $PKG/usr/man ]; then
  find $PKG/usr/man -type f -name "*.?" -exec gzip -9f {} \;
  for i in $(find $PKG/usr/man -type l -name "*.?") ; do ln -s $( readlink $i ).gz $i.gz ; rm $i ; done
fi

# Strip binaries (if any):
find $PKG | xargs file | grep -e "executable" -e "shared object" | grep ELF \
  | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null || true

# Add a package description:
mkdir -p $PKG/install
cat $SRCDIR/slack-desc > $PKG/install/slack-desc

# Build the package:
cd $PKG
makepkg --linkadd y --chown n $OUTPUT/${PRGNAM}-${VERSION}-${ARCH}-${BUILD}${TAG}.${PKGTYPE:-txz} 2>&1 | tee $OUTPUT/makepkg-${PRGNAM}.log
cd $OUTPUT
md5sum ${PRGNAM}-${VERSION}-${ARCH}-${BUILD}${TAG}.${PKGTYPE:-txz} > ${PRGNAM}-${VERSION}-${ARCH}-${BUILD}${TAG}.${PKGTYPE:-txz}.md5
cd -
cat $PKG/install/slack-desc | grep "^${PRGNAM}" > $OUTPUT/${PRGNAM}-${VERSION}-${ARCH}-${BUILD}${TAG}.txt

# Restore the original umask:
umask ${_UMASK_}

