#!/bin/bash

# instance config
CYRUSCONF=/etc/cyrus${INSTANCE}.conf
IMAPDCONF=/etc/imapd${INSTANCE}.conf

# make sure what we have is a valid instance
# and that config files are present
if [ -n "$INSTANCE" ]; then
  [ -L /etc/rc.d/init.d/cyrus-imapd${INSTANCE} ] || exit 0
fi
[ -f $CYRUSCONF ] || exit 0
[ -f $IMAPDCONF ] || exit 0

CONFDIR=$(grep -se "^configdirectory:" $IMAPDCONF | cut -d":" -f2)
if [ -z "$CONFDIR" ]; then
  echo "$0 error: configdirectory not found in ${IMAPDCONF}, exiting!"
  exit 1
fi

find $CONFDIR -type d ! -name "lost+found" -exec chmod 700 {} \; -exec chown cyrus:mail {} \;
grep -sE "^(meta|)partition-.*:" $IMAPDCONF | cut -d":" -f2 | while read SPOOLDIR; do
  if [ -z "$SPOOLDIR" ]; then
    echo "$0 warning: invalid (meta)partition configuration in $IMAPDCONF found!"
  else
    find $SPOOLDIR -type d ! -name "lost+found" -exec chmod 700 {} \; -exec chown cyrus:mail {} \;
  fi
done

find $CONFDIR -type f ! -name "lost+found" -exec chmod 600 {} \; -exec chown cyrus:mail {} \;
grep -sE "^(meta|)partition-.*:" $IMAPDCONF | cut -d":" -f2 | while read SPOOLDIR; do
  if [ -z "$SPOOLDIR" ]; then
    echo "$0 warning: invalid (meta)partition configuration in $IMAPDCONF found!"
  else
    find $SPOOLDIR -type f ! -name "lost+found" -exec chmod 600 {} \; -exec chown cyrus:mail {} \;
  fi
done

# lmtp socket must be accessible by group mail
chmod 750 $CONFDIR
chmod 750 ${CONFDIR}/socket
