#!/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 || echo "ERROR: Either you do not have vmail user permissions or the config file is missing." && exit

help()
{
  thisfilename=$(basename -- "$0")
  echo "$thisfilename"
  echo "Delete email forward from vmail database."
  echo ""
  echo "usage: $thisfilename email"
  echo ""
  echo "  -h          Print this help."
  echo ""
  echo "              Enter email in full email address format to delete forwarding."
  exit
}

# check for and set alias search term(s)
if [ -n "$1" ]; then
  if [ $1 == "-h" ]; then
    help
  elif [[ ! $1 =~ ^- ]] ; then
    email=$1
    shift
    if [[ $email =~ "@" ]] ; then
      mbox=${email%@*}
      domain=${email##*@}
      if ! vmail::validate_domain $domain; then
        echo "ERROR: $domain is not a valid domain name."
        exit 1
      fi
    else
      echo "ERROR: $email is not a valid email alias."
      help
    fi
  fi
fi

# set any options that were passed
while getopts "h" opt; do
  case "${opt}" in
    h )
      help
      exit;;
    \? )
      echo "Invalid option: $OPTARG" 1>&2
      exit;;
  esac
done

# build query
dbcmd="mysql --defaults-extra-file=$MYSQL_CONNECTION_INFO_FILE"
dbcmdopts="-s -r -N -e"

# get aliases id which also works to confirm alias exists
dbquery="SELECT vm_forwards.id FROM vm_forwards, vm_mboxes, vm_domains WHERE vm_forwards.mbox_id=vm_mboxes.id AND vm_mboxes.mbox='$mbox' AND vm_mboxes.domain_id=vm_domains.id AND vm_domains.domain='$domain';"
vm_forwards_id=`$dbcmd $dbcmdopts "$dbquery"`

if [ -z "$vm_forwards_id" ]; then
  echo "ERROR: Forward for $email does not exist."
  exit 1
elif [ "$vm_forwards_id" -gt '0' ]; then
  dbquery="DELETE FROM vm_forwards WHERE vm_forwards.id='$vm_forwards_id';"
  eval $dbcmd $dbcmdopts \"$dbquery\"
  echo "SUCCESS: Forward for $email removed from system."
  exit 0
else
  echo "ERROR: System error querying vmail database"
  exit 1
fi