#!/bin/bash
#
# vmail-stack
# https://git.stack-source.com/msb/vmail-stack
# MIT License Copyright (c) 2021 Matthew Saunders Brown
#
# vmail include file, used by other vmail bash scripts

# any script that includes this conf file will force user to be vmail
if [ "$USER" != "vmail" ]; then
  exec sudo -u vmail --shell /bin/bash $0 $@
fi

# constants
readonly VMAIL_DIR=/var/vmail
readonly MYSQL_CONNECTION_INFO_FILE=$VMAIL_DIR/.my.cnf

# check that MYSQL_CONNECTION_INFO_FILE exists and is readable
if [ ! -f "$MYSQL_CONNECTION_INFO_FILE" ]; then
  echo "ERROR: MySQL connection info file ($MYSQL_CONNECTION_INFO_FILE) does not exist or is not readable."
  exit
fi

# functions

# crude but good enough domain name format validation
function vmail::validate_domain () {
  local my_domain=$1
  if [[ $my_domain =~ ^(([a-zA-Z](-?[a-zA-Z0-9])*)\.)+[a-zA-Z]{2,}$ ]] ; then
    return 0
  else
    return 1
  fi
}

# yesno prompt
#
# Examples:
# loop until y or n:  if vmail::yesno "Continue?"; then
# default y:          if vmail::yesno "Continue?" Y; then
# default n:          if vmail::yesno "Continue?" N; then
function vmail::yesno() {

  local prompt default reply

  if [ "${2:-}" = "Y" ]; then
    prompt="Y/n"
    default=Y
  elif [ "${2:-}" = "N" ]; then
    prompt="y/N"
    default=N
  else
    prompt="y/n"
    default=
  fi

  while true; do

    read -p "$1 [$prompt] " -n 1 -r reply

    # Default?
    if [ -z "$reply" ]; then
      reply=$default
    fi

    # Check if the reply is valid
    case "$reply" in
      Y*|y*) return 0 ;;
      N*|n*) return 1 ;;
    esac

  done

}