#!/bin/bash

###########################
# User defined variables. #
###########################

MAX_EMAILS=100 # Max emails in cur/new before script should create archive.
CUR_YEAR_AGE=120 # Minimum age of email before archived.

#################################################################
# Must set owner of files to ensure correct ownership of files. #
#################################################################

if [ -z $1 ]
then
echo "set user as 1 parameter"
echo "must also be copied into email account folder next to dovecot indexing files."
exit 1
fi
USER=$1

######################
# Declare functions. #
######################

function create_archive {
FOLDER=$1
EMAILS=$(find $FOLDER -type f -mtime +$CUR_YEAR_AGE -printf "%p %Tm %TY\n") # filename month year.
MONTHS_AND_YEARS=$(echo "$EMAILS" | awk '{print $2" "$3}' | sort | uniq) # month year.
while read -r line; do
MONTH=$(echo "$line" | awk '{print $1}')
YEAR=$(echo "$line" | awk '{print $2}')
echo "[*] Creating .INBOX.$YEAR.$MONTH/cur"
sudo -u $USER mkdir -p .INBOX.$YEAR.$MONTH/cur
echo "[*] Adding .INBOX.$YEAR.$MONTH/cur to subscription."
echo "INBOX.$YEAR.$MONTH" >> subscriptions

NEXT=$(echo $(expr "$MONTH" + 1))
if [ ${#NEXT} -ne 2 ]
then
NEXT=$(echo "$NEXT" | awk '{print "0"$1}')
fi

echo "[*] Archiving emails."
if [ $NEXT -ne 13 ]
then
sudo -u $USER find $FOLDER -type f -newermt $(echo $YEAR$MONTH | awk '{print $1"01"}') -not -newermt $(echo $YEAR$NEXT | awk '{print $1"01"}') -exec mv {} .INBOX.$YEAR.$MONTH/cur \;
else
sudo -u $USER find $FOLDER -type f -newermt $(echo $YEAR$MONTH | awk '{print $1"01"}') -not -newermt $(echo $YEAR$MONTH | awk '{print $1"31"}') -exec mv {} .INBOX.$YEAR.$MONTH/cur \;
fi

done <<< "$MONTHS_AND_YEARS" } ########################################## # Check if neccesary, and run archiving. # ########################################## CURAMOUNT=$(ls -al cur | wc -l) NEWAMOUNT=$(ls -al new | wc -l) AMOUNT=$(echo $(expr "$CURAMOUNT" + "$NEWAMOUNT")) if [ $AMOUNT -gt $MAX_EMAILS ] then echo "[*] Current amount: $AMOUNT is higher than max: $MAX_EMAILS." echo "[*] cur amount: $CURAMOUNT new amount: $NEWAMOUNT" echo "[*] Running archiving job." if [ $CURAMOUNT -gt 3 ] then create_archive cur fi if [ $NEWAMOUNT -gt 3 ] then create_archive new fi echo "[*] Done." fi exit 0

Readers comments

    Leave a Reply

    Your email address will not be published. Required fields are marked *