#!/bin/bash

# To be run in the domain folder of the mail store 
# eg. /opt/kerio/mailserver/store/mail/domain.com

# Requires fdupes & rename (if macOS, be sure to install this via Homebrew)
# Debian: apt-get install fdupes
# macOS: brew install fdupes && brew install rename
# RH/Cent: yum install fdupes

# Find Duplicates and remove all but one per #msgs folder
find . -type d -name '#msgs' -exec fdupes -Nd {} \;

# Stop Kerio Connect to begin manual re-indexing
# macOS 
 /usr/local/kerio/mailserver/KerioMailServer stop
# linux
# systemctl stop kerio-connect

# Manual Re-indexing - Renaming index.fld to index.bad
find . -type f -name 'index.fld' -exec rename s/index.fld/index.bad/ {} \;

# Remove the files contributing to duplication per KB360015201419
find . -type d -name '__keriomapi__STORE' -prune -exec rm -rf {} \;
find . -type f -name '.journal.db' -exec rm -f {} \;
find . -type f -name 'specguid.fld' -exec rm -f {} \;

# Start Kerio Connect
# macOS
 /usr/local/kerio/mailserver/KerioMailServer start
# linux
# systemctl start kerio-connect
