#!/bin/bash
#
# vmail-stack
# https://git.stack-source.com/msb/vmail-stack
# MIT License Copyright (c) 2021 Matthew Saunders Brown

# load config
source /usr/local/etc/vmail.conf

help()
{
  thisfilename=$(basename -- "$0")
  echo "$thisfilename"
  echo "Get domain data from vmail database."
  echo ""
  echo "usage: $thisfilename [domain] [OPTIONS]"
  echo ""
  echo "  -e          Exact match instead of wildcard search."
  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 ""
  echo "              Domain can either be a FQDN or a search term."
  echo "              e.g. to search for all .org domains enter .org as the domain."
  echo "              Use the -e option to disable wildcard search and require exact match of FQDN."
  exit
}

# set & check $domain here

# set any options that were passed
while getopts ":s:l:q:" opt; do
  case "${opt}" in
      s )
        status=${OPTARG}
        ;;
      l )
        limit=${OPTARG}
        ;;
      q )
        quota=${OPTARG}
        ;;
      \? )
        echo "Invalid option: $OPTARG" 1>&2
        ;;
      : )
        echo "Invalid option: $OPTARG requires an argument" 1>&2
      ;;
  esac
done

# check if vmail domain dir exits
if [ -d /var/vmail/$domain ]; then
  echo "ERROR: Directory /var/vmail/$domain already exists."
  exit 1
fi

# check if domain exists in vmail database
rowcount=`mysql --defaults-extra-file=$MYSQL_CONNECTION_INFO_FILE -s -r -N -e "SELECT COUNT(*) from vm_domains WHERE domain='$domain';"`
if [ "$rowcount" -eq '0' ] ; then
  # looks good, build SQL
  cmd="mysql --defaults-extra-file=$MYSQL_CONNECTION_INFO_FILE -e \"INSERT INTO vm_domains SET domain='$domain'\""
  if [ ! -z "$status" ] ; then
    if [ "$status" == 0 ] || [ "$status" == 1 ]; then
      cmd="$cmd, status='$status'"
    else
      echo "ERROR: status (-s) must be 1 or 0"
      exit 1
    fi
  fi
  if [ ! -z "$limit" ] ; then
    if [[ "$limit" == "NULL" ]]; then
      cmd="$cmd, mbox_limit=NULL"
    elif [[ "$limit" =~ ^[0-9]+$ ]]; then
      cmd="$cmd, mbox_limit='$limit'"
    else
      echo "ERROR: limit (-l) must numeric or NULL"
      exit 1
    fi
  fi
  if [ ! -z "$quota" ] ; then
    if [[ "$quota" == "NULL" ]]; then
      cmd="$cmd, mbox_quota_default=NULL"
    elif [[ "$quota" =~ ^[0-9]+$ ]]; then
      cmd="$cmd, mbox_quota_default='$quota'"
    else
      echo "ERROR: quota (-q) must numeric or NULL"
      exit 1
    fi
  fi
  cmd="$cmd;"
  # add domain to vmail database
  echo $cmd
elif [ "$rowcount" -eq '1' ] ; then
  echo "ERROR: $domain already exists in vmail database."
  exit 1
else
  echo "ERROR: System error querying vmail database"
  exit 1
fi