#!/usr/bin/env php

<?php

// Put location of ICE headers on your PC, if you have installed ICE from source to non-standard location.
// If you installed ICE using standard package for your OS, leave as is.
$ice_path = "";

// Put location of Smartswitch header files on your PC.
// Files should be downloaded from https://your.provider.ip/ice/php/
$ice_smartswitch_path = "/usr/local/share/smartswitch/ice/php";

ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . $ice_path . PATH_SEPARATOR . $ice_smartswitch_path);

require 'Ice.php';
require 'Glacier2.php';
require 'Peer/User.php';
require 'Session.php';

$port = 10000;

if($argc != 5)
{
    echo "Usage: " . $argv[0] . " <host> <login> <password> <answer-user-name>\n".
         "      host:        ICE service provider IP address or domain name\n".
         "      login:       ICE login (same as web-access login)\n".
         "      password:    ICE password (same as web-access password)\n".
         "      answer-user: the name of a local user to which direct a call if a dialed number answers\n";
    die();
}

$host = $argv[1];
$user = $argv[2];
$password = $argv[3];
$answer_user = $argv[4];

try
{
    // Initialize a communicator using the default properties.
    $initData = new Ice\InitializationData;
    $initData->properties = Ice\createProperties();
    $initData->properties->setProperty("Ice.Default.Router", "SmartswitchGlacier2/router:ssl -p $port -h $host");
    $initData->properties->setProperty("Ice.Plugin.IceSSL", "IceSSL:createIceSSL");
    $initData->properties->setProperty("IceSSL.VerifyPeer", "0");
    $ICE = Ice\initialize($initData);

    try
    {
        // Verify that we are using a Glacier2 router.
        $router = Glacier2\RouterPrxHelper::checkedCast($ICE->getDefaultRouter());
        if($router == null)
        {
            echo "Configured router is not a Glacier2 router.\n";
            die();
        }

        $session = Smartswitch\SessionPrxHelper::uncheckedCast($router->createSession($user, $password));
    }
    catch(Glacier2\PermissionDeniedException $ex)
    {
        echo "Login failure: " . $ex->reason . "\n";
        die();
    }

    $task = $session->addCallGenerationTask();
    if($task == null)
    {
        echo "Unable to create task.\n";
        die();
    }

    // Caller Ids will be picked randomly per each call.
    $task->addCallerId("49597112233");
    $task->addCallerId("49597112244");

    // 4 Callee IDs to dial.
    $task->addCalleeId("49597111111");
    $task->addCalleeId("49597111112");
    $task->addCalleeId("49597111113");
    $task->addCalleeId("49597111114");

    // Below code is optional.
    // If you don't specify answer peer explicitly,
    // newly created task will inherit answer peer settings from previously created task.
    // Previously created task could have been created either via API or in web-interface.
    // If there is no previously created task - answer peer will be set to user, which runs this API.
    $user = $session->findUserByLogin($answer_user);
    if($user == null)
    {
        echo "Unable to find user with login " . $answer_user . ".\n";
        die();
    }
    $task->setAnswerUser($user);
    // Below code is optional.
    // If you configure state interface for answer peer,
    // Smartswitch will check peer's availability using specified interface (for example, SIP).
    // If peer is not available (either he's offline, or he's accepting another call),
    // Smartswitch won't generate new calls until answer peer becomes available.
    // Specifying state interface is useful, if answer peer is a call center agent.
    // Omitting specyfying state interface is useful, if answer peer is reached via call forwarding to a mobile/landline number.
    $task->setAnswerPeerStateInterface(Smartswitch\Telephony\CallGeneration\StateInterface::StateInterfaceSip);
    // End of optional code.

    $task->setEnabled(true); // this starts call generation

    while($task->getEndTime() == "")
    {
        echo "Waiting for task completion.\n";
        sleep(1);
    }

    echo "Waiting for CDR to be available.\n";

    // Wait for CDR to be available
    sleep(30);

    // Fetch CDRs by chunks, each of 100 records.
    for($offset = 0;; $offset += 100)
    {
        $cdr = $task->getCdr($offset);
        if(empty($cdr))
            break;

        print_r($cdr);
    }

    // Release servants on server-side.
    // Server won't allow you to allocate more than 1000 servants.
    $task->destroy();

    try
    {
         $router->destroySession();
    }
    catch(Glacier2\SessionNotExistException $ex)
    {
        // This exception is expected if the session has expired.
    }
    catch(Exception $ex)
    {
        // Ignore.
    }
    exit();
}
catch(Ice\LocalException $ex)
{
    print_r($ex);
}
?>
