#!/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 "Get email account data from vmail database."
  echo ""
  echo "usage: $thisfilename [-m <mbox>|-d <domain>|-e <email>] [OPTIONS]"
  echo ""
  echo "  -h          Print this help."
  echo "  -m <mbox>   Return all email accounts, accross all domains, with <mbox> for the local part."
  echo "  -d <domain> Return all email accounts from specified domain."
  echo "  -e <email>  Specific email address to search for."
  echo "  -c          Output in csv format."
  echo "  -t          Use tabs instead of tables for output, do not display column headers."
  echo "  -v          Include encrypt password in output."
  echo ""
  echo "              Search term is optional. If nothing specified all email acccounts for all domains will be returned."
  echo "              Examples:"
  echo "              $thisfilename -e joe@example.com # search for specific email address 'joe@example.com'."
  echo "              $thisfilename -m joe             # search for username 'joe' in all domains."
  echo "              $thisfilename -d example.com     # search for all usernames in the 'example.com' domain."
  exit
}

vmail:getoptions "$@"

dbcmd="mysql --defaults-extra-file=$MYSQL_CONNECTION_INFO_FILE"
dbcmdopts="-e"

if [[ -n $tab ]]; then
  dbcmdopts="-s -N $dbcmdopts"
fi

# build query
dbquery="SELECT mbox, domain"
if [[ -n $verbose ]]; then
  dbquery="$dbquery, passwd"
fi
dbquery="$dbquery, status, quota, ratelimit, filter FROM vm_mboxes"
if [[ -n $mbox ]] && [[ -n $domain ]]; then
  # search for specific email address
  dbquery="$dbquery WHERE mbox='$mbox' AND domain='$domain'"
elif [[ -n $mbox ]] && [[ -z $domain ]]; then
  # search all domains for username
  dbquery="$dbquery WHERE mbox='$mbox'"
elif [[ -z $mbox ]] && [[ -n $domain ]]; then
  # get all usernames for domain
  dbquery="$dbquery WHERE 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 domain, mbox;";

# execute mysql query
eval $dbcmd $dbcmdopts "\"$dbquery\"" $csv