#!/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 "Add email alias to vmail system"
  echo ""
  echo "usage: $thisfilename email alias [OPTIONS]"
  echo ""
  echo "  -h          Print this help."
  echo ""
  echo "              'email' should be the full address 'alias' just the local part (username)."
  echo "              .e.g to have info@example.com delivered (aliased) to joe@example.com do:"
  echo "              $thisfilename joe@example.com info"
  exit
}

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

# check for and set alias & email address & split in to local part & domain
if [ -n "$2" ]; then
  if [ $1 == "-h" ] || [ $2 == "-h" ]; then
    help
  else
    email=$1
    shift
    alias=$1
    shift
    if [[ $email =~ "@" ]] ; then
      mbox=${email%@*}
      domain=${email##*@}
      if [ -z $mbox ] ; then
        echo "ERROR: No local part in $email."
        exit
      elif [ -z $domain ] ; then
        echo "ERROR: No domain in $email."
        exit
      elif [[ ! $domain =~ ^(([a-zA-Z](-?[a-zA-Z0-9])*)\.)+[a-zA-Z]{2,}$ ]] ; then
        echo "ERROR: $domain is not a valid domain name."
        exit
      fi
    else
      echo "ERROR: $email is not a valid email."
      exit
    fi
  fi
else
  help
fi

# get domain_id (and thus check if domain already exists)
domain_id=`mysql --defaults-extra-file=/usr/local/etc/vmail.conf -s -r -N -e "SELECT id from vm_domains WHERE domain='$domain';"`
if [ -z $domain_id ] ; then
  echo "ERROR: Domain $domain does not exist."
  exit
fi

# get mbox id, which also verfies that email address exists
mbox_id=`mysql --defaults-extra-file=/usr/local/etc/vmail.conf -s -r -N -e "SELECT id FROM vm_mboxes WHERE domain_id='$domain_id' AND mbox='$mbox';"`
# rowcount=`mysql --defaults-extra-file=/usr/local/etc/vmail.conf -s -r -N -e "SELECT COUNT(*) FROM vm_mboxes WHERE domain_id='$domain_id' AND mbox='$mbox';"`
if [ -z $mbox_id ] ; then
  # mbox does not exist, can't create alias
  echo "ERROR: Address to Alias To ($email) does not exist."
  exit
elif [ "$mbox_id" -gt '1' ] ; then
  # verified mbox, check for existing alias
  existing_alias=`mysql --defaults-extra-file=/usr/local/etc/vmail.conf -s -r -N -e "SELECT vm_mboxes.mbox FROM vm_mboxes, vm_aliases WHERE vm_aliases.alias='$alias' AND vm_aliases.mbox_id=vm_mboxes.id AND vm_mboxes.domain_id='$domain_id';"`
  if [ -z $existing_alias ]; then
    # existing alias does not exist, add new one now
    dbcmd="mysql --defaults-extra-file=/usr/local/etc/vmail.conf -e 'INSERT INTO vm_aliases SET vm_aliases.alias=\"$alias\", vm_aliases.mbox_id=\"$mbox_id\";'"
    echo $dbcmd
  else
    if [ "$existing_alias" == "$mbox" ]; then
      echo "ERROR: Alias for $alias To $email already exists."
      exit
    else
      echo "ERROR: Alias for $alias already points to another address ($existing_alias@$domain). To update delete that alias first, then add a new one."
      exit
    fi
  fi
else
  # db query error
  echo "ERROR: System error querying vmail database."
  exit 1
fi