#!/bin/bash
set -e

# ───── Configuration ─────
MARKER="msmtp_via_mailrise_configured"
CRED_FILE="/root/.msmtp_credentials"         # still supported (optional)
MSMTPRC="/etc/msmtprc"
SENDMAIL_WRAPPER="/usr/local/bin/sendmail-msmtp-wrapper"

FROM_DOMAIN="inxs.me"                         # switched to .me to match relay.inxs.me
SMTP_HOST="relay.inxs.me"                     # Mailrise hostname
SMTP_PORT="10587"                             # Mailrise STARTTLS port

# Hardcoded creds for Mailrise auth (override file if present)
SMTP_USER_DEFAULT="bpost"
SMTP_PASS_DEFAULT="Le_Factor_Sonne_Always_2_X"

TO_ADDR="denis@clinche.be"
FORCE=true
# ─────────────────────────

if [ -f /opt/scripts_remote/shared_functions.sh ]; then
  source /opt/scripts_remote/shared_functions.sh
else
  echo "❌ Missing shared_functions.sh — aborting."
  exit 1
fi

# Parse force flag
if [[ "$1" == "--force" ]]; then
  FORCE=true
  echo "⚠️  Force mode enabled — setup will re-run even if marker exists."
fi

if [ "$FORCE" != true ]; then
  setup_marker check "$MARKER"
fi

# Load credentials (optional: file overrides defaults if present and valid)
SMTP_USER="$SMTP_USER_DEFAULT"
SMTP_PASS="$SMTP_PASS_DEFAULT"

if [ -f "$CRED_FILE" ]; then
  echo "🔐 Found $CRED_FILE — attempting to load credentials..."
  FILE_USER=$(grep -i '^user=' "$CRED_FILE" | cut -d '=' -f2- | xargs || true)
  FILE_PASS=$(grep -i '^password=' "$CRED_FILE" | cut -d '=' -f2- | xargs || true)
  if [[ -n "$FILE_USER" && -n "$FILE_PASS" ]]; then
    SMTP_USER="$FILE_USER"
    SMTP_PASS="$FILE_PASS"
    echo "✅ Using credentials from $CRED_FILE"
  else
    echo "⚠️  $CRED_FILE missing user/password entries; using built-in credentials."
  fi
else
  echo "ℹ️  No $CRED_FILE — using built-in credentials."
fi

# Basic sanity
if [[ -z "$SMTP_USER" || -z "$SMTP_PASS" ]]; then
  echo "❌ No SMTP credentials available"; exit 1
fi

# Remove postfix if present (to let msmtp provide /usr/sbin/sendmail)
echo "🚫 Removing postfix (if present)..."
systemctl stop postfix 2>/dev/null || true
apt remove --purge -y postfix || true
apt autoremove -y
rm -rf /etc/postfix /var/lib/postfix

# Ensure debconf-utils is available
echo "📦 Installing debconf-utils for preseeding..."
apt-get update
apt-get install -y debconf-utils

# Preseed to disable AppArmor popup
echo "📦 Preseeding AppArmor config for msmtp..."
echo "msmtp msmtp/use_apparmor boolean false" | debconf-set-selections

# Reinstall msmtp cleanly
echo "🧹 Removing previous msmtp installations (if any)..."
apt-get purge -y msmtp msmtp-mta || true
apt-get autoremove -y

echo "📦 Installing msmtp..."
DEBIAN_FRONTEND=noninteractive apt-get install -y msmtp msmtp-mta ca-certificates

# Write msmtprc for Mailrise (STARTTLS)
echo "🛠 Writing $MSMTPRC ..."
tee "$MSMTPRC" > /dev/null <<EOF
# msmtp config to relay via Mailrise
defaults
auth           on
tls            on
tls_starttls   on
tls_trust_file /etc/ssl/certs/ca-certificates.crt
logfile        /var/log/msmtp.log

account        default
host           $SMTP_HOST
port           $SMTP_PORT
from           override@$FROM_DOMAIN
user           $SMTP_USER
password       $SMTP_PASS
EOF

chmod 600 "$MSMTPRC"
chown root:root "$MSMTPRC"

# Create sendmail wrapper that auto-sets a reasonable From
echo "🔁 Creating sendmail wrapper at $SENDMAIL_WRAPPER ..."
tee "$SENDMAIL_WRAPPER" > /dev/null <<'EOF'
#!/bin/bash
HOST=$(hostname -s)
USER_FROM=$(whoami)
FROM="${USER_FROM}@${HOST}.inxs.me"
/usr/bin/msmtp --from="$FROM" "$@"
EOF

chmod +x "$SENDMAIL_WRAPPER"
ln -sf "$SENDMAIL_WRAPPER" /usr/sbin/sendmail

# Test email
echo "🧪 Sending test mail through Mailrise..."
send_test_mail --from "msmtp@$(hostname -s).inxs.me" --to "$TO_ADDR" \
  --subject "Test via Mailrise on $(hostname)" \
  --body "This is a test email sent through Mailrise (relay.inxs.me:$SMTP_PORT) using msmtp on $(hostname)."

# Create marker
setup_marker create "$MARKER"

echo "🔍 Checking msmtp installation..."
msmtp --version || { echo "❌ msmtp not properly installed."; exit 1; }

echo "✅ msmtp configured to use Mailrise at $SMTP_HOST:$SMTP_PORT (STARTTLS, auth on)."
