#!/bin/bash

# A POSIX variable
OPTIND=1         # Reset in case getopts has been used previously in the shell.

# Initialize our own variables:
output_file=""
archive=0
days_old=-1

while getopts "a:d:" opt; do
    case "$opt" in
    a)  archive=1
        output_file="$OPTARG.tar"
        ;;
    d)  days_old=$OPTARG
        ;;
    esac
done

shift $((OPTIND-1))

if [ "$days_old" -lt 0 ];then
    echo "You must specify the age in days for mail to be purged/archived using the -d option"
    echo "usage: ./purge-email.sh [-a file path] [-d days old]"
    echo "    -a Archive the old mail before deleting. If -a is specified then you must also supply a file path for the gzipped tar file to be saved to (no file extension)"
    echo "    -d Days old mail should be before it is deleted/archived (required)"
    exit
fi
if [ "$archive" == 1 ];then
    if [ "$output_file" == "" ];then
        echo "If you specify the -a (archive) option then you must also provide a file path for the archive to be saved to"
        echo "usage: ./purge-email.sh [-a file path] [-d days old]"
        echo "    -a Archive the old mail before deleting. If -a is specified then you must also supply a file path for the gzipped tar file to be saved to"
        echo "    -d Days old mail should be before it is deleted/archived (required)"
        exit
    else
        echo "archiving mail older than $days_old days"
        find /usr/local/atmail/users/ -type f -ctime +$days_old -path */cur/* | xargs -I{} tar --atime-preserve=system --preserve rvPf $output_file {} && rm -f {}
        if [ -e "$output_file" ];then
            gzip $output_file;
        else
            echo "No archive created, possibly no email more than $days_old days old found"
        fi
    fi
else
    echo "Purging all email older than $days_old days"
    find /usr/local/atmail/users/ -type f -ctime +$days_old -path */cur/* -delete
fi
