<?php
$webmailDir  = dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR;
$wwwUser = ( isset($_SERVER['argv'][1]) ) ? $_SERVER['argv'][1] : 'atmail';
$wwwGroup  = ( isset($_SERVER['argv'][2]) ) ? $_SERVER['argv'][2] : '';

if( !file_exists($webmailDir . '.VERSION') )
{
	die("\n*******************\n Failed: Unable to find expected .VERSION file in webmail root path\n****************\n"); 
}

$client = false;
$rootServerDir = dirname($webmailDir) . DIRECTORY_SEPARATOR;
if( !is_dir($rootServerDir . 'mailserver'))
{
	$client = true;
}

$touchfiles = array(
	$webmailDir . 'log/error.log',
	$webmailDir . 'log/atmail.log',
	$webmailDir . 'log/imap.log',
	$webmailDir . 'log/sysadmin.log'
);

$directories = array(
		$webmailDir . '.',
		$webmailDir . 'bootloader.php',
		$webmailDir . 'sync.php',
		$webmailDir . 'index.php',
		$webmailDir . 'log',
		$webmailDir . 'tmp',
		$webmailDir . 'users'
);

if(!$client)
{
	$directories = array_merge($directories,
			array(
				$rootServerDir . 'spamassassin',
				$rootServerDir . 'tmp',
				$rootServerDir . 'mailserver',
				$rootServerDir . 'av',
				$rootServerDir . 'calendarserver',
				$rootServerDir . 'users'
			)
	);

	// Make sure session.save_path is writable by webserver user, used by the Admin session (file based)
	$sessionSavePath = trim(session_save_path());
	if(empty($sessionSavePath))
	{
		$sessionSavePath = sys_get_temp_dir();
	}

	if(is_dir($sessionSavePath))
	{
		$directories = array_merge($directories, array(	$sessionSavePath ));
	}
}


echo "Changing .htaccess permissions for $webmailDir...\n";
system('find "' . $webmailDir . '" -name .htaccess -exec chmod 644 {} \;');
system('find "' . $webmailDir . '" -name .htaccess -exec chown root:root {} \;');

if($client) exit(1);

foreach( $touchfiles as $file )
{
	echo "Touching " . $file . "...";
	system("touch $file");
	echo "\n";
}


foreach( $directories as $dir )
{
	if( file_exists("$dir") )
	{
		echo "Changing ownership to $wwwUser" . (empty($wwwGroup) ? '' : ':' . $wwwGroup) . " for $dir ...";
		system("chown -R $wwwUser $dir");
		if( !empty($wwwGroup) )
		{
				system("chgrp -R $wwwGroup $dir");
		}
		echo "\n";
	}
}

echo "\nCompleted.";
