#!/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 domain data from vmail database."
  echo ""
  echo "usage: $thisfilename [-d <domain>|-g <glob>] [OPTIONS]"
  echo ""
  echo "  -h          Print this help."
  echo "  -d          Domain to be queried."
  echo "  -g          Glob - Wildcard search instead of specific domain search."
  echo "  -c          Output in csv format."
  echo "  -t          Use tabs instead of tables for output, do not display column headers."
  echo ""
  echo "              Domain/Glob is optional. If nothing specified all domains will be queried."
  echo "              Domain search is for an exact match."
  echo "              Use -g instead of -d for glog (wildcard) search. e.g:"
  echo "              $thisfilename -g stack  # search for all domains that contain 'stack'."
  exit
}

vmail:getoptions "$@"

dbcmd="mysql --defaults-extra-file=$MYSQL_CONNECTION_INFO_FILE"
dbcmdopts="-e"
if [[ -n $tab ]]; then
  dbcmdopts="-s -N $dbcmdopts"
fi
dbquery="SELECT domain, status, mbox_limit, (SELECT COUNT(*) FROM vm_mboxes WHERE vm_mboxes.domain = vm_domains.domain) as mbox_allocated, mbox_quota_default, mbox_ratelimit_default from vm_domains"

# build query
if [[ -n $domain ]]; then
  dbquery="$dbquery WHERE domain='$domain'"
elif [[ -n $glob ]]; then
  dbquery="$dbquery WHERE domain LIKE '%$glob%'"
fi

# sort results by domain name
dbquery="$dbquery ORDER BY domain"

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