#!/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 'Session.php';

$port = 10000;

if($argc != 7)
{
    echo "Usage: " . $argv[0] . " <host> <login> <password> <callback-caller-name> <callback-callee-number> <dial-number>\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".
         "      callback-caller-name:   displayed on the 'callback' party phone\n".
         "      callback-callee-number: put external number or internal extension like '100'\n".
         "      dial-number:            the number to be dialed when callback call is answered\n";
    die();
}

$host = $argv[1];
$user = $argv[2];
$password = $argv[3];
$callbackCallerName = $argv[4];
$callbackCalleeNumber = $argv[5];
$dialNumber = $argv[6];

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();
    }

    $session->callback($callbackCallerName,
                       $callbackCalleeNumber,
                       $dialNumber,
                       Smartswitch\Telephony\CallbackMode::SyncDialAnswer);

    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);
}
?>
