#!/bin/bash
#let'S update roundcube emails if primary domain has changed

# exit if this migration is disabled by admin
STATUS=`config getprop roundcube RewritePrimary || echo "enabled"`
if [[ "$STATUS" == "disabled" ]]; then
exit 0
fi


#get previous primary domain
OLDDOMAIN=`config getprop sysconfig PreviousDomainName||echo "empty"`
# exit if does not exist
if [[ "$OLDDOMAIN" == "empty" ]]; then
  exit 0
fi
# get current primary domain
NEWDOMAIN=`config get DomainName||echo "empty"`
# exit if it is empty: something wrong !
if [[ "$NEWDOMAIN" == "empty" ]]; then
  exit 0
fi
# exit fi previous is same as current = no change yet
if [[ "$NEWDOMAIN" == $OLDDOMAIN ]]; then
  exit 0
fi

# exit if old domain is still present, we might have add it back and manually added some entires we do not want to change
db domains gettype $OLDDOMAIN || exit 0

roundcube=`config getprop roundcube DbName || echo "roundcube"`

# testing
#echo 'SELECT `email`, REPLACE(`email`,substr( `email`,CHAR_LENGTH(`email`) - LOCATE("@", REVERSE(`email`))+2),"'$NEWDOMAIN'" ) as newemail FROM `identities` WHERE `email` LIKE "%@'$OLDDOMAIN'";'|mariadb $roundcube

#updating
echo 'UPDATE IGNORE  `identities` SET `email`= REPLACE(`email`,substr( `email`,CHAR_LENGTH(`email`) - LOCATE("@", REVERSE(`email`))+2),"'$NEWDOMAIN'" ) WHERE `email` LIKE "%@'$OLDDOMAIN'";' |mariadb $roundcube
