<?php

/*
CalendarServer 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_v3/debug.php";

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

$db="data/caldb_v2.sqlite";
dbg_init("cal.log");

//print ('hello');
//return;

dbg("----");
dbg("Sabre CAL 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_CALLBACK, "assert_callcack");

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

$baseUri = "/cal";
$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);

$calendarBackend = new Sabre\CalDAV\Backend\PDO($pdo);
$principalBackend = new Sabre\DAVACL\PrincipalBackend\PDO($pdo);

//$foo = $calendarBackend instanceof  Sabre\CalDAV\Backend\SharingSupport;

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

$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);


// OPTIONAL NEW STUFF!!!
/* CalDAV Sharing support */
//$server->addPlugin(new Sabre\DAV\Sharing\Plugin());
//$server->addPlugin(new Sabre\CalDAV\SharingPlugin());
/* Calendar scheduling support */
//$server->addPlugin(
//    new Sabre\CalDAV\Schedule\Plugin()
//);
/* WebDAV-Sync plugin */
//$server->addPlugin(new Sabre\DAV\Sync\Plugin());
/* Calendar subscription support */
//$server->addPlugin(
//    new Sabre\CalDAV\Subscriptions\Plugin()
//);


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

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

dbg("Sabre CAL END");
