#!/bin/sh /etc/rc.common

START=95
STOP=10
USE_PROCD=1

NAME="mailserver"

start_service() {
	local enabled=$(uci -q get mailserver.main.enabled)
	[ "$enabled" = "1" ] || {
		echo "Mail server is disabled. Enable with: uci set mailserver.main.enabled=1"
		return 0
	}

	local container=$(uci -q get mailserver.main.container)
	container="${container:-mailserver}"

	if ! lxc-info -n "$container" >/dev/null 2>&1; then
		echo "Container '$container' not found. Create with: mailctl install"
		return 1
	fi

	echo "Starting mail server container: $container"
	lxc-start -n "$container"
}

stop_service() {
	local container=$(uci -q get mailserver.main.container)
	container="${container:-mailserver}"

	if lxc-info -n "$container" 2>/dev/null | grep -q "RUNNING"; then
		echo "Stopping mail server container: $container"
		lxc-stop -n "$container" -t 30
	fi
}

reload_service() {
	local container=$(uci -q get mailserver.main.container)
	container="${container:-mailserver}"

	if lxc-info -n "$container" 2>/dev/null | grep -q "RUNNING"; then
		echo "Reloading mail server services..."
		lxc-attach -n "$container" -- postfix reload 2>/dev/null
		lxc-attach -n "$container" -- doveadm reload 2>/dev/null
	fi
}

status() {
	local container=$(uci -q get mailserver.main.container)
	container="${container:-mailserver}"

	if lxc-info -n "$container" 2>/dev/null | grep -q "RUNNING"; then
		echo "Mail server: Running"
		lxc-attach -n "$container" -- postfix status 2>/dev/null
	else
		echo "Mail server: Stopped"
	fi
}
