#!/bin/bash
#  _____               _           _
# |   __|___ ___ ___ _| |___ _____| |_ ___ ___ ___
# |   __|  _| -_| -_| . | . |     | . | . |   | -_|
# |__|  |_| |___|___|___|___|_|_|_|___|___|_|_|___|
#
#                              Freedom in the Cloud
#
# Archives old email

# License
# =======
#
# Copyright (C) 2015-2019 Bob Mottram <bob@freedombone.net>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

PROJECT_NAME='freedombone'

export TEXTDOMAIN=${PROJECT_NAME}-archive-mail
export TEXTDOMAINDIR="/usr/share/locale"

source "/usr/share/${PROJECT_NAME}/utils/${PROJECT_NAME}-utils-validation"

for d in /home/*/ ; do
    USERNAME=$(echo "$d" | awk -F '/' '{print $3}')
    if [[ $(is_valid_user "$USERNAME") == "1" ]]; then
        # for every user who has a mail directory
        if [ -d "/home/$USERNAME/Maildir" ]; then
            MUTTRC=/home/$USERNAME/.muttrc
            # update archives
            python /usr/bin/cleanup-maildir --archive-folder="archive" --maildir-root="/home/$USERNAME/Maildir" archive ""
            # ensure the user has permissions on the archives
            for archive_dir in /home/$USERNAME/Maildir/archive-* ; do
                chown -R "$USERNAME":"$USERNAME" "$archive_dir"
            done
            # add the archive to .muttrc if needed
            if [ -f "$MUTTRC" ]; then
                MUTT_MAILBOXES=$(grep "mailboxes =" "$MUTTRC")
                YR=$(date +"%Y")
                PREV_YR=$((YR - 1))
                BACKUP_DIRECTORY=archive-$YR
                PREV_BACKUP_DIRECTORY=archive-$PREV_YR
                if [[ $MUTT_MAILBOXES != *$BACKUP_DIRECTORY* ]]; then
                    if [[ $MUTT_MAILBOXES == *$PREV_BACKUP_DIRECTORY* ]]; then
                        sed -i "s|$PREV_BACKUP_DIRECTORY|$PREV_BACKUP_DIRECTORY =$BACKUP_DIRECTORY|g" "$MUTTRC"
                    else
                        sed -i "s|$MUTT_MAILBOXES|$MUTT_MAILBOXES =$BACKUP_DIRECTORY|g" "$MUTTRC"
                    fi
                    chown "$USERNAME":"$USERNAME" "$MUTTRC"
                fi
            fi
        fi
    fi
done

exit 0