vmail-stack/bin/vmail-mboxes-get.sh
2021-04-02 12:02:50 -07:00

103 lines
3.2 KiB
Bash
Executable File

#!/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
help()
{
thisfilename=$(basename -- "$0")
echo "$thisfilename"
echo "Get email account data from vmail database."
echo ""
echo "usage: $thisfilename [username|domain|fullemail] [OPTIONS]"
echo ""
echo " -c Output in cvs format."
echo " -h Print this help."
echo " -s Be more silent - use tabs instead of tables for output, do not display column headers."
echo " -w Wildcard search when searching for username."
echo ""
echo " Search term is optional. If nothing specified all email acccounts for all domains will be returned."
echo " By default username searches are for exact matchs."
echo " Specify -w to turn them in to a wildcard search. Examples:"
echo " $thisfilename joe@example.com # search for specific email address 'joe@example.com'."
echo " $thisfilename joe # search for username 'joe' in all domains."
echo " $thisfilename joe -w # search for usernames containing 'joe' in all domains."
echo " $thisfilename example.com # search for all usernames in the 'example.com' domain."
exit
}
dbcmd="mysql --defaults-extra-file=$MYSQL_CONNECTION_INFO_FILE"
dbcmdopts="-e"
dbquery="SELECT vm_mboxes.mbox, vm_domains.domain, vm_mboxes.status, vm_mboxes.quota FROM vm_domains, vm_mboxes WHERE vm_domains.id=vm_mboxes.domain_id"
# check for and set email search term(s)
if [ -n "$1" ]; then
if [ $1 == "-h" ]; then
help
elif [[ ! $1 =~ ^- ]] ; then
searchterm=$1
shift
if [[ $searchterm =~ "@" ]] ; then
mbox=${searchterm%@*}
domain=${searchterm##*@}
elif vmail::validate_domain $searchterm; then
domain=$searchterm
else
mbox=$searchterm
fi
fi
fi
# set any options that were passed
while getopts "chsw" opt; do
case "${opt}" in
c )
cvs="| sed 's/\t/,/g'"
;;
h )
help
exit;;
s )
dbcmdopts="-s -N $dbcmdopts"
;;
w )
wildcardsearch=true
;;
\? )
echo "Invalid option: $OPTARG" 1>&2
exit;;
esac
done
# build query
if [ -n "$mbox" ] && [ -n "$domain" ]; then
# search for specific email address
dbquery="$dbquery AND vm_domains.domain='$domain' AND vm_mboxes.mbox='$mbox'"
elif [ -n "$mbox" ] && [ -z "$domain" ]; then
# search all domains for username
if [ -n "$wildcardsearch" ]; then
# wildcard search
dbquery="$dbquery AND vm_mboxes.mbox LIKE '%$mbox%'"
else
# exact match
dbquery="$dbquery AND vm_mboxes.mbox='$mbox'"
fi
elif [ -z "$mbox" ] && [ -n "$domain" ]; then
# get all usernames for domain
dbquery="$dbquery AND vm_domains.domain='$domain'"
# elif [ -z "$mbox" ] && [ -z "$domain" ]; then
# echo "ERROR: No username or domain specified."
# help
# uncomment above 3 lines to force search term, otherwise all email addresses for all domains will be returned
fi
# set order by
dbquery="$dbquery ORDER BY vm_domains.domain, vm_mboxes.mbox;";
# execute mysql query
eval $dbcmd $dbcmdopts "\"$dbquery\"" $cvs