#!/bin/sh
# emailwiz - plan/apply/validate a Postfix + Dovecot + OpenDKIM mail server on Debian 13
#
# Copyright (C) 2026 contributors to this Debian 13 fork of emailwiz
# Derived from emailwiz by Luke Smith and contributors
#   https://github.com/LukeSmithxyz/emailwiz (reference revision aefc7a8)
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version. See LICENSE.
# SPDX-License-Identifier: GPL-3.0-or-later

set -eu
umask 022
export LC_ALL=C PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

EMAILWIZ_VERSION=2.0.0

_self=$0
while [ -L "$_self" ]; do
	_l=$(readlink "$_self")
	case $_l in /*) _self=$_l ;; *) _self=$(dirname "$_self")/$_l ;; esac
done
EMAILWIZ_ROOT=$(cd "$(dirname "$_self")" && pwd)

for _lib in common config detect postfix dovecot opendkim services tls firewall engine validate ops setup; do
	# shellcheck disable=SC1090
	. "$EMAILWIZ_ROOT/lib/$_lib.sh"
done

usage() {
	cat <<EOF
emailwiz $EMAILWIZ_VERSION - Debian 13 mail server management (emailwiz successor)

usage: emailwiz COMMAND [options]

Read-only:
  audit                       report platform, packages, services, emailwiz leftovers
  plan [--component C] [--detailed-exitcode] [--no-diff]
                              show the changes apply would make (changes nothing;
                              --detailed-exitcode exits 10 if changes are pending)
  validate [--no-dns] [--deliver-test] [--external-test ADDR] [--renew-test]
                              check config, services, TLS, relay policy, DNS;
                              --deliver-test sends a local test message,
                              --external-test sends one to ADDR (explicit opt-in),
                              --renew-test runs certbot renew --dry-run
  dns                         print the DNS records this host needs
  cert-check [--notify]       certificate expiry check (used by the timer)
  backups                     list backups

Changes:
  setup [--non-interactive]   guided first install: config, packages, firewall,
                              certificate, apply, first account, validation
  init [DOMAIN]               write /etc/emailwiz/emailwiz.conf from detected values
  install-packages            install missing Debian packages (never purges)
  apply [--component C] [--yes]
                              back up, install the desired config, validate, reload
  backup [--with-mail]        snapshot configuration + DKIM keys (+ ~/Mail)
  rollback BACKUP_ID [--yes]  restore a configuration snapshot
  tls-obtain                  obtain the certbot certificate (TLS_MODE=certbot)
  firewall [--yes]            add UFW allow rules for the mail ports (TCP only)
  migrate-upstream [--fix-pam]
                              one-time cleanup of upstream emailwiz leftovers
  user add NAME | user list   manage mail accounts (system users in group mail)

Components: $COMPONENTS
Exit codes: 0 ok, 1 error, 2 usage, 3 validation failed, 4 unsupported OS, 10 changes pending
Config: \$EMAILWIZ_CONF (default /etc/emailwiz/emailwiz.conf)
EOF
}

preflight() {
	detect_os
	config_load
	config_validate
	_m=$(missing_packages)
	[ -z "$_m" ] || die "missing packages: $_m (run: sudo emailwiz install-packages)" "$EX_ERR"
	detect_versions
	[ -r "$TLS_CERT" ] || die "TLS_CERT $TLS_CERT not readable"
	[ -r "$TLS_KEY" ] || die "TLS_KEY $TLS_KEY not readable"
}

cmd=${1:-help}
[ $# -gt 0 ] && shift
case $cmd in
audit) cmd_audit "$@" ;;
plan) cmd_plan "$@" ;;
apply) cmd_apply "$@" ;;
validate) cmd_validate "$@" ;;
dns) cmd_dns "$@" ;;
cert-check) cmd_cert_check "$@" ;;
backup) cmd_backup "$@" ;;
backups) cmd_backups "$@" ;;
rollback) cmd_rollback "$@" ;;
init) cmd_init "$@" ;;
setup) cmd_setup "$@" ;;
tls-obtain) cmd_tls_obtain "$@" ;;
firewall) cmd_firewall "$@" ;;
install-packages) cmd_install_packages "$@" ;;
migrate-upstream) cmd_migrate_upstream "$@" ;;
user) cmd_user "$@" ;;
version | --version) echo "emailwiz $EMAILWIZ_VERSION" ;;
help | -h | --help) usage ;;
*) usage >&2; exit "$EX_USAGE" ;;
esac
