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

/**
 * ec2host
 *
 * @copyright Copyright (c) fruux GmbH. All rights reserved.
 * @author Dominik Tobschall (http://fruux.com/)
 */

/*
 * Find the Composer autoloader.
 * Credit: https://github.com/evert/sabre-vobject/blob/master/bin/vobjectvalidate.php
 */

$paths = [
    __DIR__ . '/../vendor/autoload.php',  // In case the project is cloned directly
    __DIR__ . '/../../../autoload.php',   // In case the project is a composer dependency.
];

foreach ($paths as $path) {
    if (file_exists($path)) {
        include($path);
        break;
    }
}

/* Setting a default timezone so PHP doesn't emit any warnings */
date_default_timezone_set('UTC');


/*
 * Import namespaces
 */
use ec2dns\ec2;
use ec2dns\ec2host;

/*
 * Instantiate main class.
 */
try {
    $ec2 = new ec2(getenv('AWS_ACCESS_KEY_ID'), getenv('AWS_SECRET_ACCESS_KEY'), getenv('EC2_URL'));
} catch (Exception $e) {
    fwrite(STDERR, $e->getMessage() . "\n");
    die();
}

/*
 * Run ec2host
 */
if (isset($argv[1])) {
    $ec2host = new ec2host($ec2, $argv[1]);
} else {
    $ec2host = new ec2host($ec2);
}

/*
 * Output result of ec2host
 */
foreach ($ec2host->instances as $instance) {
    if (isset($argv[1])) {
        echo $instance['dnsName'] . "\n";
    } else {
        echo $instance['instanceId'] . ": " . $instance['tag'] . "\t" . $instance['dnsName'] . "\n";
    }
}
