<?php

/*
CardDAV Server example
NetWin implemented based on modified SabreDAV implementation
VERSION:2

designed to be used with :
	- sabredav version 3.2.2
	- php version 7.3.11 (should work 7+)
*/

$phplib=getenv("SURGEMAIL_ROOT")."/phplib";
require_once "$phplib/netwin_v2/debug.php";

//require_once "$phplib/".getenv("SABRE_VERSION")."/lib/Sabre/autoload.php";
require_once "$phplib/sabredav_3.2.2/vendor/autoload.php";
require_once "$phplib/netwin_v2/Nwauth_sabre.php";

$db="data/abkdb_v2.sqlite";
dbg_init("abk.log");

dbg("----");
dbg("Sabre ABK v2");

error_reporting(E_ALL | E_STRICT);
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_BAIL, 0);
assert_options(ASSERT_QUIET_EVAL, 0);
assert_options(ASSERT_CALLBACK, "assert_callcack");

if(getenv("CLUSTER_MASTER")!='TRUE'){
    print("ERROR: calendaring can only be used on the MASTER of a mirrorred cluster");
    return;
}

$baseUri = "/abk";
$pdo = new PDO("sqlite:$db");
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
	throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
set_error_handler("exception_error_handler");

//$authBackend = new Sabre\DAV\Auth\Backend\PDO($pdo);
//$authBackend = new Sabre\DAV\Auth\Backend\File($davdata.'/.htdigest');
$authBackend = new Sabre\DAV\Auth\Backend\Nwauth($pdo);
$principalBackend = new Sabre\DAVACL\PrincipalBackend\PDO($pdo);

//$calendarBackend = new Sabre\CalDAV\Backend\PDO($pdo);
$carddavBackend = new Sabre\CardDAV\Backend\PDO($pdo);


$tree = array(
	new Sabre\CalDAV\Principal\Collection($principalBackend),
//	new Sabre\CalDAV\CalendarRoot($principalBackend, $calendarBackend),
	new Sabre\CardDAV\AddressBookRoot($principalBackend, $carddavBackend),
);

$server = new Sabre\DAV\Server($tree);
if (isset($baseUri))
	$server->setBaseUri($baseUri);

$authPlugin = new Sabre\DAV\Auth\Plugin($authBackend);
$server->addPlugin($authPlugin);

// OLD STUFF TO KEEP
$aclPlugin = new Sabre\DAVACL\Plugin();
$server->addPlugin($aclPlugin);

//$caldavPlugin = new Sabre\CalDAV\Plugin();
//$server->addPlugin($caldavPlugin);
$carddavPlugin = new Sabre\CardDAV\Plugin();
$server->addPlugin($carddavPlugin );


// Support for html frontend
$browser = new Sabre\DAV\Browser\Plugin();
$server->addPlugin($browser);

// And off we go!
$server->exec();

dbg("Sabre ABK END");
