#!/bin/bash

# shellcheck source=../scripts/helpers/index.sh
source /usr/local/bin/helpers/index.sh

function _main() {
  _require_n_parameters_or_print_usage 1 "${@}"

  # Tests expect early exit without error if no DB exists:
  [[ -s ${DATABASE_ACCOUNTS} ]] || return 0

  _maildel_request_if_missing

  # TODO: May want to lock all database files prior to loop? (DATABASE_ACCOUNTS DATABASE_QUOTA DATABASE_VIRTUAL)
  # NOTE: Present lock method locks the original sourcing script itself.
  _create_lock

  # Actual command to perform:
  for MAIL_ACCOUNT in "${@}"; do
    _account_should_already_exist

    if [[ ${MAILDEL} -eq 1 ]]; then
      _remove_maildir "${MAIL_ACCOUNT}"
    elif [[ ${MAILDEL} -eq 2 ]]; then
      _log 'info' "Mailbox data explicitly kept (using -n)."
    else
      _log 'info' "The mailbox data will not be deleted."
    fi

    _manage_virtual_aliases_delete '_' "${MAIL_ACCOUNT}" \
      || _exit_with_error "Aliases for '${MAIL_ACCOUNT}' could not be deleted"

    _manage_dovecot_quota_delete "${MAIL_ACCOUNT}" \
      || _exit_with_error "Quota for '${MAIL_ACCOUNT}' could not be deleted"

    # Performed last, avoids breaking command if a prior failure occurred
    _manage_accounts_delete "${MAIL_ACCOUNT}" \
      || _exit_with_error "'${MAIL_ACCOUNT}' could not be deleted"

    _log 'info' "'${MAIL_ACCOUNT}' and associated data (aliases, quotas) deleted"
  done
}

function __usage() {
  printf '%s' "${PURPLE}delmailuser${RED}(${YELLOW}8${RED})

${ORANGE}USAGE${RESET}
    ./setup.sh email del [ OPTIONS ] <MAIL ACCOUNT> [<EXTRA MAIL ACCOUNTS> ${RED}...${RESET} ]

${ORANGE}OPTIONS${RESET}
    -y
        Skip prompt by approving to ${LWHITE}delete all mail data${RESET} for the account(s).
    -n
        Skip prompt by declining to ${LWHITE}delete all mail data${RESET} for the account(s).

    ${BLUE}Generic Program Information${RESET}
        help       Print the usage information.

${ORANGE}DESCRIPTION${RESET}
    Delete a mail account, including associated data (aliases, quotas) and
    optionally the mailbox data for that account.

${ORANGE}EXAMPLES${RESET}
    ${LWHITE}./setup.sh email del user@example.com${RESET}
        Delete the mail account 'user@example.com' and associated data,
        but ask if mailbox data should also be deleted.

    ${LWHITE}./setup.sh email del -y user@example.com extra-user@example.com${RESET}
        Delete the two mail accounts requested, their associated data and
        delete the mailbox data for both accounts without asking.

    ${LWHITE}./setup.sh email del -n user@example.com extra-user@example.com${RESET}
        Delete the two mail accounts requested, their associated data and DO NOT
        delete the mailbox data for both accounts without asking.

${ORANGE}EXIT STATUS${RESET}
    Exit status is 0 if command was successful. If wrong arguments are provided
    or arguments contain errors, the script will exit early with exit status 1.

"
}

function _parse_options() {
  while getopts ":yYnN" OPT; do
    case "${OPT}" in
      ( 'y' | 'Y' )
        MAILDEL=1
        ;;
      ( 'n' | 'N' )
        MAILDEL=2
        ;;
      ( * )
        __usage
        _exit_with_error "The option '${OPT}' is unknown"
        ;;

    esac
  done
}

function _maildel_request_if_missing() {
  if [[ ${MAILDEL} -eq 0 ]]; then
    local MAILDEL_CHOSEN
    read -r -p "Do you want to delete the mailbox data as well (removing all mails)? [y/N] " MAILDEL_CHOSEN

    # Delete mailbox data only if the user provides explicit confirmation.
    [[ ${MAILDEL_CHOSEN,,} == "y" ]] && MAILDEL=1
  fi
}

function _remove_maildir() {
  local MAIL_ACCOUNT=${1}

  local LOCAL_PART="${MAIL_ACCOUNT%@*}"
  local DOMAIN_PART="${MAIL_ACCOUNT#*@}"
  local MAIL_ACCOUNT_STORAGE_DIR="/var/mail/${DOMAIN_PART}/${LOCAL_PART}"

  [[ ! -d ${MAIL_ACCOUNT_STORAGE_DIR} ]] && _exit_with_error "Mailbox data directory '${MAIL_ACCOUNT_STORAGE_DIR}' does not exist"

  _log 'info' "Deleting mailbox data: '${MAIL_ACCOUNT_STORAGE_DIR}'"
  rm -R "${MAIL_ACCOUNT_STORAGE_DIR}" || _exit_with_error 'Mailbox data could not be deleted'
  # Remove parent directory too if it's empty:
  rmdir "/var/mail/${DOMAIN_PART}" &>/dev/null
}

# Support for optional maildir removal:
MAILDEL=0
_parse_options "${@}"
# Remove options before passing over parameters to _main:
shift $((OPTIND-1))

_main "${@}"
