<?

function getHost(Bool $parent = false) {
  $arHost = explode( ":", $_SERVER["HTTP_HOST"]);
  $_SERVER["HTTP_HOST"] = $arHost[0];
  $hostname = $_SERVER['HTTP_HOST'];

  if ($parent) {
    $hostname_parts = explode('.', $hostname);

    if (count($hostname_parts) > 2) {
      array_shift($hostname_parts);
      $hostname = implode('.', $hostname_parts);
    }
  }

  return $hostname;
}

function echoTextFile($hostname) {
	$path = $_SERVER['DOCUMENT_ROOT'];
  // $path = str_replace('/' . getHost(), '', $_SERVER['DOCUMENT_ROOT']);
  // $path = str_replace('/' . getHost(true), '', $_SERVER['DOCUMENT_ROOT']);

	// $file = $path . '/' . $hostname . "/" . trim($_SERVER['REQUEST_URI'], '/');
	$file = $path . "/" . trim($_SERVER['REQUEST_URI'], '/');

	$file = str_replace('sitemap.xml', 'sitemap_.xml', $file);
	// $file = str_replace('sitemap-', 'sitemap/', $file);

	// echo'<pre>';print_r($_SERVER['DOCUMENT_ROOT']);echo'</pre>';
	// echo'<pre>';print_r($file);echo'</pre>';
	// echo'<pre>';var_dump(file_exists($file));echo'</pre>';exit;

	if (!file_exists($file)) return false;
	if (!is_readable($file)) return false;
	if (!filesize($file)) return false;

	// echo'<pre>';print_r($file);echo'</pre>';exit;

	$timestamp = filemtime($file);
	$tsstring = gmdate('D, d M Y H:i:s ', $timestamp) . 'GMT';
	$etag = md5($file . $timestamp);

  $xml = file_get_contents($file);
	$xml = str_replace('https://', 'https://', $xml);
	$xml = str_replace('https://' . getHost(true) , 'https://' . getHost() , $xml);

	// $xml = str_replace('sitemap/', 'sitemap-', $xml);

	header('Content-Type: application/xml');
	header('Content-Length: '.mb_strlen($xml));
	header("Last-Modified: $tsstring");
  header("ETag: \"{$etag}\"");

	echo $xml;

	return true;
}

if(!echoTextFile(getHost()) && !echoTextFile(getHost(true))) 
{
	header('HTTP/1.0 404 Not Found');
}