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

$port = 10000;

if($argc != 5)
{
    echo "Usage: " . $argv[0] . " <host> <login> <password> <voucher-code>\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".
         "      voucher-code: a code of voucher which to check\n";
    die();
}

$host = $argv[1];
$user = $argv[2];
$password = $argv[3];
$code = $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();
    }

    $voucher = $session->findRefillVoucher($code);
    if($voucher == null)
        echo "No such voucher.\n";
    else
        print_r($voucher->getAmount());

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