#!/bin/sh
# postinst script for indimail
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

prefix=/usr
version=1.3
indimaildir=/var/indimail
mandir=/usr/share/man
libexecdir=/usr/libexec/indimail
qcount=5
qbase=${indimaildir}/queue
logdir=/var/log/svc
servicedir=/service
sysconfdir=/etc/indimail
cp=/bin/cp
rm=/bin/rm
mv=/bin/mv
####################################
nocourierimap=0
nofetchmail=0
nodksignature=0
dkimkeyfn=default
default_domain=indimail.org
build_on_obs=0

setperm()
{
	local user="$1"; shift
	local group="$1"; shift
	local mode="$1"; shift
	local file="$1"; shift
	/usr/sbin/dpkg-statoverride --list "$file" >/dev/null && return 0
	/usr/sbin/dpkg-statoverride --update --add "$user" "$group" "$mode" "$file"
}

fixperms()
{
#%attr(0555,root,qmail) /usr/bin/rsmtp
	if [ $# -eq 3 ] ; then # directory
		lin=$2
		file=$3
		if [ ! -d $file ] ; then
			return 0
		fi
	elif [ $# = 2 ] ; then # file
		lin=$1
		file=$2
		if [ ! -f $file ] ; then
			return 0
		fi
	fi
	perm=`echo $lin|cut -d\( -f2 | cut -d, -f1`
	perm_f1=`echo $perm | cut -c1`
	own=`echo $lin|cut -d\( -f2 | cut -d, -f2`
	grp=`echo $lin|cut -d\( -f2 | cut -d, -f3|cut -d\) -f1`
	if [ -f $file ] ; then
		if [ $perm_f1 -eq 0 ] ; then # perm_f1 is 4755, 0644
			/bin/chown $own:$grp $file
			/bin/chmod $perm $file
		else
			echo $file
			if [ -f /usr/sbin/dpkg-statoverride ] ; then
				setperm $own $grp $perm $file
			else
				/bin/chown $own:$grp $file
				/bin/chmod $perm $file
			fi
		fi
	elif [ -d $file ] ; then
		/bin/chown $own:$grp $file
		/bin/chmod $perm $file
	fi
}

ID=`id -u`
if [ $ID -ne 0 ] ; then
	echo "You are not root" >&2
	exit 1
fi

upgrade=0
case "$1" in
	configure)
	if [ -n "$2" ] ; then
		upgrade=1
	fi
	;;

	abort-upgrade|abort-remove|abort-deconfigure)
	exit 0
	;;

	*)
	echo "postinst called with unknown argument \`$1'" >&2
	exit 1
	;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

#
# We need to do this for debian. SIGH!!
#
if [ -f ${sysconfdir}/perm_list.imap ] ; then
	echo "Fixing Permissions"
	(
	/bin/grep -v "^#" ${sysconfdir}/perm_list.imap | while read line
	do
		if [ " $line" = " " ] ; then
			continue
		fi
		fixperms $line
	done
	) > ${sysconfdir}/indimail-access-stat.override
fi

# indimail-access.upgrade/indimail-access.install are created
# by the preinst script
if [ $upgrade -eq 1 ] ; then # upgrade
  svc_list=""
  for i in qmail-imapd.143 qmail-imapd-ssl.993 \
    qmail-pop3d.110 qmail-pop3d-ssl.995
  do
	if [ ! -d ${servicedir}/$i ] ; then
		continue
	fi
    if [ -z "$svc_list" ] ; then
      svc_list="${servicedir}/$i"
    else
      svc_list="$svc_list ${servicedir}/$i"
    fi
  done
  ${prefix}/sbin/svctool --servicedir=${servicedir} --refreshsvc="$svc_list"
  set +e
  if [ -d /run ] ; then
    rundir=/run
  elif [ -d /var/run ] ; then
    rundir=/var/run
  else
    rundir=${servicedir}
  fi
  for i in qmail-imapd.143 qmail-imapd-ssl.993 \
    qmail-pop3d.110 qmail-pop3d-ssl.995 \
    fetchmail
  do
	if [ ! -d ${servicedir}/$i ] ; then
		continue
	fi
    ${prefix}/bin/svok ${servicedir}/$i >/dev/null 2>&1
    if [ $? -eq 0 -a -f ${rundir}/$i/.down ] ; then
	  rm -f ${rundir}/$i/.down
      ${prefix}/bin/svc -u ${servicedir}/$i >/dev/null 2>&1
    fi
  done
  set -e
  exit 0
fi
# Recreate ld.so links and cache
if [ ! "${prefix}" = "/usr" ] ; then
  /sbin/ldconfig
fi

echo "Doing Post Install"
echo ""
echo "1. Configure ${logdir} for multilog"
echo "2. Configure ${servicedir}"
echo "3. Configure fetchmail service"
echo "4. Configure IMAP/POP3 services"
echo "5. Configure tcprules database for IMAP, POP3"
echo ""

if [ -x /bin/touch ] ; then
  TOUCH=/bin/touch
elif [ -x /usr/bin/touch ] ; then
  TOUCH=/usr/bin/touch
else
  TOUCH=/bin/touch
fi
(
echo "Creating ${logdir}"
for i in fetchmail imapd.143 imapd-ssl.993 pop3d.110 pop3d-ssl.995
do
  /bin/mkdir -p ${logdir}/$i
  /bin/chown -R qmaill:nofiles ${logdir}/$i
done

if [ -d /run ] ; then
  logfifo="/run/indimail/logfifo"
elif [ -d /var/run ] ; then
  logfifo="/var/run/indimail/logfifo"
else
  logfifo="/tmp/logfifo"
fi

if [ $build_on_obs -eq 0 ] ; then
	if [ -x /usr/bin/uname -o -x /bin/uname ] ; then
		default_domain=$(echo $([ -n "$HOSTNAME" ] && echo "$HOSTNAME" || uname -n) | sed 's/^\([^\.]*\)\.\([^\.]*\)\./\2\./')
	else
		default_domain=$([ -n "$HOSTNAME" ] && echo "$HOSTNAME" | sed 's/^\([^\.]*\)\.\([^\.]*\)\./\2\./' || echo ${default_domain})
	fi
fi
a_arch=`uname -m`
if [ " $a_arch" = " x86_64" ] ; then
 fetchmail_mem=104857600
 imap_pop3_mem=104857600
 imapspop3_mem=104857600
else
 fetchmail_mem=52428800
 imap_pop3_mem=52428800
 imapspop3_mem=52428800
fi

if [ $nofetchmail -eq 0 ] ; then
	# fetchmail
	if [ $nodksignature -eq 0 ] ; then
		if [ -f ${sysconfdir}/control/domainkeys/default ] ; then
			ver_opt="both"
		else
			ver_opt="none"
		fi
	else
		ver_opt="none"
	fi
	extra_opt=""
	if [ -x ${prefix}/bin/bogofilter ] ; then
		extra_opt="--spamfilter=\"${prefix}/bin/bogofilter -p -d ${sysconfdir}\""
		extra_opt="$extra_opt --logfilter=$logfifo --rejectspam=0 --spamexitcode=0"
	fi
	if [ -f /usr/sbin/clamd -a -f /usr/bin/clamdscan ] ; then
		qhpsi="/usr/bin/clamdscan %s --config=${sysconfdir}/scan.conf --fdpass --quiet --no-summary"
		extra_opt="$extra_opt --qhpsi=\"$qhpsi\""
	fi
	eval ${prefix}/sbin/svctool --fetchmail --servicedir=$servicedir \
		--qbase=${qbase} --qcount=${qcount} --qstart=1 \
		--cntrldir=control \
		--memory=$fetchmail_mem --fsync --syncdir \
		--dkverify=$ver_opt \
		$extra_opt
	#
	# user has to create fetchmailrc before which fetchmail cannot be started
	#
	/bin/touch $servicedir/fetchmail/down
fi

# IMAP/POP3
if [ $nocourierimap -eq 0 ] ; then
	${prefix}/sbin/svctool --imap=143 --servicedir=$servicedir --localip=0 \
		--maxdaemons=40 --maxperip=25 --infifo=infifo --default-domain=${default_domain} \
		--starttls --memory=$imap_pop3_mem
	${prefix}/sbin/svctool --imap=993 --servicedir=$servicedir --localip=0 \
		--maxdaemons=40 --maxperip=25 --infifo=infifo --default-domain=${default_domain} \
		--memory=$imapspop3_mem --ssl
	${prefix}/sbin/svctool --pop3=110 --servicedir=$servicedir --localip=0 \
		--maxdaemons=40 --maxperip=25 --infifo=infifo --default-domain=${default_domain} \
		--starttls --memory=$imap_pop3_mem
	${prefix}/sbin/svctool --pop3=995 --servicedir=$servicedir --localip=0 \
		--maxdaemons=40 --maxperip=25 --infifo=infifo --default-domain=${default_domain} \
		--memory=$imapspop3_mem --ssl

	# add courier-imap auth module authindi
	echo "adding authindi as IMAP/POP3 auth module"
	set +e
	if [ -f ${libexecdir}/imapmodules/authindi ] ; then
		for i in `ls -d ${servicedir}/qmail-pop3d* ${servicedir}/qmail-imapd*`
		do
			if [ -s $i/variables/IMAPMODULES ] ; then
				grep authindi $i/variables/IMAPMODULES > /dev/null
				if [ $? -ne 0 ] ; then
					AUTHM="`cat $i/variables/IMAPMODULES` authindi"
					echo $AUTHM > $i/variables/IMAPMODULES
				fi
			fi
		done
	fi
	set -e
fi

# rebuild cdb
for i in imap pop3 poppass
do
	for j in `/bin/ls ${sysconfdir}/tcp/tcp.$i 2>/dev/null`
	do
		t1=`date +'%s' -r $j`
		if [ -f $j.cdb ] ; then
			t2=`date +'%s' -r $j.cdb`
		else
			t2=0
		fi
		if [ $t1 -gt $t2 ] ; then
			echo "Creating CDB $j.cdb"
			${prefix}/bin/tcprules $j.cdb $j.tmp < $j && /bin/chmod 664 $j.cdb \
				&& /bin/chown indimail:indimail $j.cdb
		fi
	done
done

if [ -f ${mandir}/man7/authlib.7 ] ; then
	gzip ${mandir}/man7/authlib.7
fi
if [ -f ${mandir}/man7/authlib.7.gz ] ; then
	for i in authshadow.7 authpwd.7 authpam.7 authcustom.7
	do
		${rm} -f ${mandir}/man7/$i
		ln -sf ${mandir}/man7/authlib.7.gz ${mandir}/man7/$i.gz
	done
fi
# turn off automatic refresh for services during first time installation
svc_list=""
for i in fetchmail qmail-imapd.143 qmail-imapd-ssl.993 \
  qmail-pop3d.110 qmail-pop3d-ssl.995
do
  if [ ! -d ${servicedir}/$i ] ; then
    continue
  fi
  svc_list="$svc_list ${servicedir}/$i"
  ${prefix}/sbin/svctool --servicedir=${servicedir} --service-name=$i \
    --export-variables=${servicedir}/$i/variables/.variables  --force
done
${prefix}/sbin/svctool --servicedir=${servicedir} --autorefresh="0 $svc_list"
) >> /var/log/indimail-access-setup.log 2>&1
echo
echo "Check /var/log/indimail-access-setup.log for the detailed installation log!!!"
exit 0
