vmail-stack/bin/vmail-aliases-del.sh
2022-08-22 13:34:20 -07:00

82 lines
2.9 KiB
Bash
Executable File

#!/bin/bash
#
# vmail-stack
# https://git.stack-source.com/msb/vmail-stack
# Copyright (c) 2022 Matthew Saunders Brown <matthewsaundersbrown@gmail.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# load include file
source $(dirname $0)/vmail.sh
help()
{
thisfilename=$(basename -- "$0")
echo "$thisfilename"
echo "Delete email alias from vmail database."
echo ""
echo "usage: $thisfilename -d <domain>|-e <email> -a <alias>"
echo ""
echo " -h Print this help."
echo " -a <alias> Alias to be deleted. Local part only."
echo " -d <domain> Domain of alias to delete."
echo " -e <email> Email that alias directs to to delete."
echo ""
echo " Enter <domain> OR <email>. If <email> is specified"
echo " then just the alias to that address is deleted. If"
echo " domain is specific then all <alias>@<domain> aliases"
echo " are deleted (aliases can direct to multiple emails)."
}
vmail:getoptions "$@"
# check for alias
if [[ -z $alias ]]; then
echo "alias is required"
exit
fi
# start building query
dbcmd="mysql --defaults-extra-file=$MYSQL_CONNECTION_INFO_FILE"
dbcmdopts="-s -r -N -e"
# if email set delete single alias
if [[ -n $email ]]; then
# get aliases id which also works to confirm alias exists
dbquery="SELECT vm_aliases.id FROM vm_aliases, vm_mboxes, vm_domains WHERE vm_aliases.alias='$alias' AND vm_aliases.mbox_id=vm_mboxes.id AND vm_mboxes.mbox='$mbox' AND vm_mboxes.domain_id=vm_domains.id AND vm_domains.domain='$domain'"
vm_aliases_id=`$dbcmd $dbcmdopts "$dbquery"`
if [[ -z $vm_aliases_id ]]; then
echo "ERROR: Alias $alias@$domain -> $email does not exist."
exit 1
elif [ "$vm_aliases_id" -gt '0' ]; then
dbquery="DELETE FROM vm_aliases WHERE vm_aliases.id='$vm_aliases_id'"
echo $dbquery
eval $dbcmd $dbcmdopts "\"$dbquery\""
echo "SUCCESS: Alias $alias@$domain -> $email removed from system."
exit 0
else
echo "ERROR: System error querying vmail database"
exit 1
fi
# if domain set then delete any and all aliases
elif [[ -n $domain ]]; then
# get alias id array
dbquery="SELECT vm_aliases.id FROM vm_aliases, vm_mboxes, vm_domains WHERE vm_aliases.alias='$alias' AND vm_aliases.mbox_id=vm_mboxes.id AND vm_mboxes.domain_id=vm_domains.id AND vm_domains.domain='$domain'"
mapfile -t vm_alias_ids < <( $dbcmd $dbcmdopts "$dbquery" )
if [[ -z $vm_alias_ids ]]; then
echo "ERROR: Alias $alias@$domain does not exist."
exit 1
elif [[ ${#vm_alias_ids[@]} -gt '0' ]]; then
for vm_alias_id in "${vm_alias_ids[@]}"; do
dbquery="DELETE FROM vm_aliases WHERE vm_aliases.id='$vm_alias_id'"
eval $dbcmd $dbcmdopts "\"$dbquery\""
done
echo "SUCCESS: Alias(s) for $alias@$domain removed from system."
else
echo "ERROR: Unknown error. vm_alias_count=0?"
exit 1
fi
else
echo "You must specify either <domain> or <email>."
exit 1
fi