#!/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 alias data from vmail database."
  echo ""
  echo "usage: $thisfilename [-a <alias>|-e <email>|-d <domain>] [-c] [-t] [-h]"
  echo ""
  echo "  -h          Print this help."
  echo "  -a          Return info for specific alias."
  echo "  -e          Return all aliases for specified email address."
  echo "  -d          Return all aliases for specified domain."
  echo "  -c          Output in cvs format."
  echo "  -t          Use tabs instead of tables for output, do not display column headers."
  echo ""
  echo "              Search term is optional. If nothing specified all aliases for all email acccounts for all domains will be returned."
  echo "              Enter email address to get all aliases that route to that email address."
  echo "              Enter alias (in full email address format) with the -a option to get address that alias delivers to."
  echo "              Enter domain name to get all aliases for all email addresses under that domain."
  exit
}

vmail:getoptions "$@"

# set initial db query data
dbcmd="mysql --defaults-extra-file=$MYSQL_CONNECTION_INFO_FILE"
dbcmdopts="-e"
dbquery="SELECT vm_aliases.alias, vm_mboxes.mbox, vm_domains.domain FROM vm_aliases, vm_mboxes, vm_domains WHERE vm_aliases.mbox_id = vm_mboxes.id AND vm_mboxes.domain_id = vm_domains.id"

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

if [[ -n $alias ]]; then
  if [[ -n $domain ]] ; then
    dbquery="$dbquery AND vm_aliases.alias='$alias' AND vm_domains.domain='$domain'"
  else
    echo "ERROR: alias should be in full email address format."
    exit 1
  fi
elif [[ -n $email ]]; then
  dbquery="$dbquery AND vm_aliases.alias='$mbox' AND vm_domains.domain='$domain'"
elif [[ -n $domain ]]; then
  dbquery="$dbquery AND vm_domains.domain='$domain'"
else
  echo "You must specify either <alias> or <email> or <domain>."
  exit 1
fi

# set order by
dbquery="$dbquery ORDER BY vm_domains.domain, vm_mboxes.mbox, vm_aliases.alias;";

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