#!/bin/bash
# 
# Convert Vpopmail from --enable-big-user-dir to --disable-big-user-dir
#

#
# Stop services
#
qmailctl stop
systemctl stop dovecot

#
# Backup vpopmail MySQL DB and Maildir DB
#
cp -Rp /home/vpopmail/domains /home/vpopmail/domains.bak
credfile=~/sql.cnf
mysqldump --defaults-extra-file=$credfile vpopmail > vpopmail.sql

#
# Move MaildirDB
#
DOMDIR=/home/vpopmail/domains
mysql --defaults-extra-file=$credfile vpopmail -s -N -e "select pw_dir, concat('$DOMDIR','/',pw_domain,'/',pw_name), pw_domain from vpopmail" | \
while read BIG NOTBIG DOMAIN; do
   if [ "$BIG" == "$NOTBIG" ]; then 
      continue
   fi
   mv $BIG $DOMDIR/$DOMAIN
done

#
# Remove big user dirs
#
find  $DOMDIR -maxdepth 2 -type d -empty
find  $DOMDIR -maxdepth 2 -type d -empty -delete
find  $DOMDIR -maxdepth 2 -type d -empty

#
# Convert MySQL users' DB to reflect Maildir DB
#
mysql --defaults-extra-file=$credfile vpopmail -e "UPDATE vpopmail set pw_dir=REGEXP_REPLACE(pw_dir, '\/([0-9]+)\/', '/')"

#
# Update packages
#
dnf -y update \
https://downloads.whitehorsetc.com/vpopnobig/ezmlm-0.53.324-4.qt.md.el9.x86_64.rpm \
https://downloads.whitehorsetc.com/vpopnobig/ezmlm-cgi-0.53.324-4.qt.md.el9.x86_64.rpm \
https://downloads.whitehorsetc.com/vpopnobig/qmail-1.03-3.3.12.qt.md.el9.x86_64.rpm \
https://downloads.whitehorsetc.com/vpopnobig/qmailadmin-1.2.16-5.3.qt.md.el9.x86_64.rpm \
https://downloads.whitehorsetc.com/vpopnobig/vpopmail-5.4.33-7.qt.md.el9.x86_64.rpm \
https://downloads.whitehorsetc.com/vpopnobig/vqadmin-2.3.7-5.qt.md.el9.x86_64.rpm

#
# Start services
#
qmailctl start
systemctl start dovecot



exit 0
