#!/bin/bash
# ──────────────────────────────────────────────
# 📤 Send test email via msmtp
# Parameters:
#   --from    Custom sender (default: <user>@<host>.inxs.be)
#   --to      Recipient email (default: $TO_ADDR or fallback to admin@inxs.be)
#   --subject Subject line (default: "Test from <hostname>")
#   --body    Email body (default: "MSMTP configured successfully on <hostname>")
#   --debug   Enable msmtp debug output and log email to /tmp/msmtp_test_email.txt
#   --help    Show this help message and exit
# ──────────────────────────────────────────────

  from="${USER}@$(hostname -s).inxs.be"
  to="${TO_ADDR:-admin@inxs.be}"
  subject="Test from $(hostname)"
  body="MSMTP configured successfully on $(hostname)"
  debug=false

  if [[ "$1" == "--help" ]]; then
    echo "📤 Usage: send_test_mail [options]"
    echo ""
    echo "Options:"
    echo "  --from <email>     Sender address (default: ${USER}@<host>.inxs.be)"
    echo "  --to <email>       Recipient address (default: \$TO_ADDR or admin@inxs.be)"
    echo "  --subject <text>   Subject line (default: \"Test from <hostname>\")"
    echo "  --body <text>      Email body (default: \"MSMTP configured successfully on <hostname>\")"
    echo "  --debug            Enable msmtp debug output and save message to /tmp/msmtp_test_email.txt"
    echo "  --help             Show this help message and exit"
    return 0
  fi

  # Parse named arguments
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --from)    from="$2"; shift 2 ;;
      --to)      to="$2"; shift 2 ;;
      --subject) subject="$2"; shift 2 ;;
      --body)    body="$2"; shift 2 ;;
      --debug)   debug=true; shift ;;
      *)         echo "❌ Unknown parameter: $1. Use --help for usage."; return 1 ;;
    esac
  done

  echo "📤 Preparing test email..."
  echo "📨 From: $from"
  echo "📩 To: $to"
  echo "📝 Subject: $subject"

  if ! command -v msmtp >/dev/null 2>&1; then
    echo "❌ msmtp command not found. Cannot send test email."
    return 1
  fi

  local message="From: $from
To: $to
Subject: $subject

$body
"

  if $debug; then
    echo "$message" | tee /tmp/msmtp_test_email.txt | msmtp --debug --from="$from" "$to"
  else
    echo "$message" | msmtp --from="$from" "$to"
  fi

  if [[ $? -eq 0 ]]; then
    echo "✅ Test email successfully sent to $to."
  else
    echo "❌ Failed to send test email via msmtp."
    return 1
  fi
