#!/usr/bin/env php
<?php

/**
 * This file is part of cocur/domain.
 *
 * (c) Florian Eckerstorfer <florian@eckerstorfer.co>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

require_once __DIR__.'/../vendor/autoload.php';

use Cocur\Domain\Connection\ConnectionFactory;
use Cocur\Domain\Data\DataLoader;
use Cocur\Domain\Whois\Client;
use Cocur\Domain\Whois\WhoisException;
use Cocur\Domain\Whois\QuotaExceededException;

if ($_SERVER['argc'] < 2) {
    echo "Usage: php whois.php DOMAIN_NAME\n";
    exit(1);
}
$domainName = $_SERVER['argv'][1];

$verbose = false;
if ($_SERVER['argc'] >= 3 && ('-v' === $_SERVER['argv'][2] || '--verbose' === $_SERVER['argv'][2])) {
    $verbose = true;
}

$factory = new ConnectionFactory();
$dataLoader = new DataLoader();
$data = $dataLoader->load(__DIR__.'/../data/tld.json');

$client = new Client($factory, $data);
try {
    echo $client->query($domainName)."\n";
} catch (WhoisException $e) {
    if (true === $verbose) {
        throw new \Exception('Could not perform WHOIS request.', 0, $e);
    } else {
        echo "Could not perform WHOIS request:\n";
        echo "> ".$e->getMessage()."\n";
    }
} catch (QuotaExceededException $e) {
    if (true === $verbose) {
        throw new \Exception('Quota exceeded for WHOIS server.', 0, $e);
    } else {
        echo "Quota exceeded for WHOIS request:\n";
        echo "> ".$e->getMessage()."\n";
    }
}
