#!/bin/sh -eu

OCC="${OCC:-/var/www/html/occ}"
#
# For this user, obtain lines formatted as: EmailAccountId:Email
#
get_mail_accounts() {
	"$OCC" mail:account:export "$1" | \
		grep -E '^([^-]|- E-Mail)' | tr -d '\n' | \
		sed -Ee 's!(Account|- E-Mail: )!!g' | tr -d ' ' '\n' || true
}

# User-specific
user_id="$1"
account_name="$2"
email="$3"
email_password="$4"
# Server settings
inbound_host="$5"
inbound_port="$6"
inbound_ssl_mode="$7"
outbound_host="$8"
outbound_port="$9"
outbound_ssl_mode="${10}"

existing_mail_accounts="$(get_mail_accounts "$user_id")"

if [ -n "${existing_mail_accounts:-}" ]; then
    # Use the first one, it was likely created by DD
    account_id="$(echo "${existing_mail_accounts}" | head -n 1 | cut -d ':' -f 1)"
fi

if [ -z "${account_id:-}" ]; then
    # Create account
    "$OCC" mail:account:create \
	"$user_id" "$account_name" "$email" \
	"$inbound_host" "$inbound_port" "$inbound_ssl_mode" \
	"$email" "$email_password" \
	"$outbound_host" "$outbound_port" "$outbound_ssl_mode" \
	"$email" "$email_password"
else
    # Update account
    "$OCC" mail:account:update \
	--imap-host "$inbound_host" --imap-port "$inbound_port" --imap-ssl-mode "$inbound_ssl_mode" \
	--imap-user "$email" --imap-password "$email_password" \
	--smtp-host "$outbound_host" --smtp-port "$outbound_port" --smtp-ssl-mode "$outbound_ssl_mode" \
	--smtp-user "$email" --smtp-password "$email_password" \
	--name "$account_name" --email "$email" \
	-- "$account_id"
fi
