#!/bin/bash

PATH=/sbin/e-smith:/sbin:/bin:/usr/sbin:/usr/bin

BCC=$(db configuration getprop qpsmtpd Bcc || echo 'disabled')
ARCHIVE=$(db configuration getprop qpsmtpd ArchiveBcc || echo 'disabled')

# Exit now if BCC is disabled
if [ "$BCC" != "enabled" -o "$ARCHIVE" != "enabled" ]; then
  exit 0
fi

USER=$(db configuration getprop qpsmtpd BccUser || echo 'maillog')
# Truncate if it's a mail address
USER=${USER%@*}
HOME="/home/e-smith/files/users/$USER"

# Stop here if the home dir doesn't exist
if [ \! -d $HOME ]; then
  echo "$HOME doesn't exist"
  exit 1
fi

MONTH=$(date +%m)
YEAR=$(date +%Y)

su - -s /bin/bash $USER -c "maildirmake -f $YEAR $HOME/Maildir" 2>&1 > /dev/null
su - -s /bin/bash $USER -c "maildirmake -f $YEAR.$MONTH $HOME/Maildir"

# Lock mail delivery
chmod +t $HOME
cd $HOME
find Maildir/cur/ -type f | xargs -I __INPUT__ mv __INPUT__ Maildir/.$YEAR.$MONTH/cur/ 2>&1 > /dev/null
find Maildir/new/ -type f | xargs -I __INPUT__ mv __INPUT__ Maildir/.$YEAR.$MONTH/new/ 2>&1 > /dev/null
su - -s /bin/bash $USER -c "tar -c --use-compress-program=pbzip2 -f $HOME/mails_$YEAR.$MONTH.tar.bz2 Maildir/.$YEAR.$MONTH/"
su - -s /bin/bash $USER -c "rm -rf Maildir/.$YEAR.$MONTH/"
# Unlock mail delivery
chmod -t $HOME

