#!/bin/bash
#
# vmail-stack
# https://git.stack-source.com/msb/vmail-stack
# MIT License Copyright (c) 2021 Matthew Saunders Brown

# load include file
source $(dirname $0)/vmail.sh

# only continue if vmail dir exists
if [ -d $VMAIL_DIR ]; then

  # set arrays of dirs that will be purged of emails older than 30 days
  dirs=('.Junk' '.Trash');
  subdirs=('new' 'cur');

  # set vars used for db queries
  dbcmd="mysql --defaults-extra-file=$MYSQL_CONNECTION_INFO_FILE"
  dbcmdopts="-s -r -N -e"

  # purge email accounts that no longer exist in vmail db
  cd $VMAIL_DIR
  # get array of vmail domains
  vmail_domain_array=(`ls -1`)
  # make sure there are one or more domains in array
  if [ ${#vmail_domain_array[@]} -gt 0 ]; then
    # iterate thru each domain
    for vmail_domain in "${vmail_domain_array[@]}"; do
      # make sure domain array element is a dir
      if [ -d $VMAIL_DIR/$vmail_domain ]; then
        # get domain id for later queries and which also works to confirm domain exists in vmail db
        dbquery="SELECT vm_domains.id FROM vm_domains WHERE vm_domains.domain='$vmail_domain'"
        domain_id=''
        domain_id=`$dbcmd $dbcmdopts "$dbquery"`
        if [ -z "$domain_id" ]; then
          # domain does not exist in vmail db, remove domain dir now
          cd $VMAIL_DIR
          /usr/bin/rm -r ./$vmail_domain
        else
          # get list of mailboxes for domain
          cd $VMAIL_DIR/$vmail_domain
          mbox_array=(`ls -1`)
          if [ ${#mbox_array[@]} -gt 0 ]; then
            # cycle thru each mailbox for this domain
            for mbox in "${mbox_array[@]}"; do
              # get email address id which works to confirm address exists
              dbquery="SELECT vm_mboxes.id FROM vm_mboxes WHERE vm_mboxes.mbox='$mbox' AND vm_mboxes.domain_id='$domain_id'"
              mboxes_id=''
              mboxes_id=`$dbcmd $dbcmdopts "$dbquery"`
              if [ -z "$mboxes_id" ]; then
                # mailbox does not exist in vmail db, remove mbox dir now
                /usr/bin/rm -r ./$mbox
              elif [ "$mboxes_id" -gt 0 ]; then
                # check for and purge Junk & Trash folders
                for dir in "${dirs[@]}"; do
                  for subdir in "${subdirs[@]}"; do
                    if [ -d "$VMAIL_DIR/$vmail_domain/$mbox/Maildir/$dir/$subdir" ]; then
                      /usr/bin/find $VMAIL_DIR/$vmail_domain/$mbox/Maildir/$dir/$subdir -type f -mtime +30 -exec rm -f {} +
                    fi
                  done
                done
              fi
            done
          fi
        fi
      fi
    done
  fi

fi