<?php
require_once 'demosettings.php';

$action = $argv[1];
$folder = $argv[2];
if (!IS_CLI || !$action || !is_dir($folder))
	die("ImportExport.php Import|Export FOLDER");

$returnVar = 0;
$options = "--host=$databaseHost --user=$databaseUser --password=$databasePass";

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN')
{
	$copyPrefix = "xcopy";
	$copySuffix = "/A /I /S";
	$folderSeparator = "\\";
}
else
{
	$copyPrefix = "cp -r";
	$copySuffix = "";
	$folderSeparator = "/";
}

if ($action == "Export")
{
	if (count(scandir($folder)) !== 2) die("Folder is not empty: $folder");
	
	foreach (array("cnm", "cnm_text") as $databaseName)
	{
		system("mysqldump $options --databases $databaseName > \"$folder/$databaseName.sql\"", $returnVar);
		if ($returnVar !== 0) die("dumping db $databaseName returned $returnVar");
	}
	//echo "$copyPrefix \"$metadata_path\" \"$folder/metadata\" $copySuffix";
	system("$copyPrefix \"$metadata_path\" \"$folder/metadata\" $copySuffix", $returnVar);
	if ($returnVar !== 0) die("copying metadata folder returned $returnVar");
	system("del \"$folder${folderSeparator}metadata${folderSeparator}*_res.xml\"");
	system("del \"$folder${folderSeparator}metadata${folderSeparator}result_*.xml\"");
}
else if ($action == "Import")
{
	if (is_dir($metadata_path)) die("Folder exists: $metadata_path");
	
	foreach (array("cnm", "cnm_text") as $databaseName)
	{
		$sqlFile = "$folder/$databaseName.sql";
		if (!is_file($sqlFile)) die("File doesn't exist: $sqlFile");
		system("mysql $options $databaseName < \"$sqlFile\"", $returnVar);
		if ($returnVar !== 0) die("importing db $databaseName returned $returnVar");
	}
	system("$copyPrefix \"$folder/metadata\" \"$metadata_path\" $copySuffix", $returnVar);
	if ($returnVar !== 0) die("copying metadata folder returned $returnVar");
}
else die ("action ($action) should be either 'Import' or 'Export");

?>