<?php
/**
 * ONOXSOFT Thunderbird / iOS / Generic Autoconfig Endpoint
 *
 * Thunderbird, K-9 Mail, Apple Mail bu URL'i dener (Mozilla autoconfig):
 *   https://autoconfig.<domain>/mail/config-v1.1.xml?emailaddress=user@domain
 *   https://<domain>/.well-known/autoconfig/mail/config-v1.1.xml
 *
 * Schema:
 *   https://wiki.mozilla.org/Thunderbird:Autoconfiguration:ConfigFileFormat
 *
 * Deployed to: /usr/local/onoxsoft/autodiscover/thunderbird.xml.php
 */

declare(strict_types=1);

$emailAddress = isset($_GET['emailaddress']) ? (string) $_GET['emailaddress'] : '';
$requestedDomain = '';

if ($emailAddress !== '' && str_contains($emailAddress, '@')) {
    $requestedDomain = strtolower(substr(strrchr($emailAddress, '@'), 1));
}

if ($requestedDomain === '') {
    $host = $_SERVER['HTTP_HOST'] ?? '';
    $requestedDomain = preg_replace('/^(autodiscover|autoconfig)\./i', '', strtolower($host));
}

if (! preg_match('/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/i', $requestedDomain ?? '')) {
    http_response_code(400);
    header('Content-Type: text/plain');
    echo "Invalid domain\n";
    exit;
}

$mailHost = getenv('ONOX_MAIL_HOST') ?: 'mail.' . $requestedDomain;
$imapPort = (int) (getenv('ONOX_MAIL_IMAP_PORT') ?: 993);
$smtpPort = (int) (getenv('ONOX_MAIL_SMTP_PORT') ?: 587);
$providerId = 'onox.com.tr';

$confFile = '/etc/onoxsoft/mail.conf';
if (is_readable($confFile)) {
    $conf = @parse_ini_file($confFile, false, INI_SCANNER_RAW) ?: [];
    $mailHost = $conf['hostname'] ?? $mailHost;
    $imapPort = (int) ($conf['imap_port'] ?? $imapPort);
    $smtpPort = (int) ($conf['smtp_port'] ?? $smtpPort);
}

$xmlDomain = htmlspecialchars($requestedDomain, ENT_XML1 | ENT_COMPAT, 'UTF-8');
$xmlHost = htmlspecialchars($mailHost, ENT_XML1 | ENT_COMPAT, 'UTF-8');

header('Content-Type: application/xml; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate');

echo <<<XML
<?xml version="1.0" encoding="utf-8"?>
<clientConfig version="1.1">
  <emailProvider id="{$providerId}">
    <domain>{$xmlDomain}</domain>
    <displayName>{$xmlDomain}</displayName>
    <displayShortName>{$xmlDomain}</displayShortName>
    <incomingServer type="imap">
      <hostname>{$xmlHost}</hostname>
      <port>{$imapPort}</port>
      <socketType>SSL</socketType>
      <authentication>password-cleartext</authentication>
      <username>%EMAILADDRESS%</username>
    </incomingServer>
    <outgoingServer type="smtp">
      <hostname>{$xmlHost}</hostname>
      <port>{$smtpPort}</port>
      <socketType>STARTTLS</socketType>
      <authentication>password-cleartext</authentication>
      <username>%EMAILADDRESS%</username>
    </outgoingServer>
    <documentation url="https://onox.com.tr/help/mail-setup">
      <descr lang="tr">E-posta kurulum yardımı</descr>
      <descr lang="en">Mail account setup help</descr>
    </documentation>
  </emailProvider>
</clientConfig>
XML;
