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

/**
 * ec2dnshelper
 *
 * @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;
    }
}

/*
 * Die if parameter is not set
 */
if (!isset($argv[1])) {
    fwrite(STDERR, "Nothing to do here!\n");
    die();
}

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

$matchedHost = null;

/*
 * Replace known tags with hostnames
 * (This needs optimization!)
 */
$ec2host = new ec2host($ec2);
if ($ec2host->instances) {

    $arguments = array_slice($argv, 1);
    foreach ($arguments as $argumentKey => $argumentValue) {

        if (strpos($argumentValue, '-', 0) === 0 || strpos($argumentValue, '--', 0) === 0) {
            continue;
        }

        foreach ($ec2host->instances as $instance) {

            if ($instance['tag'] == $ec2host->emptyTag) {
                continue;
            }

            $newArgumentValue = preg_replace('/(^.*@?)(' .  preg_quote($instance['tag'], '/') . ')(:?.*$)/i', '$1' . $instance['dnsName'] . '$3', $argumentValue);
            if ($newArgumentValue != $argumentValue) {
                $arguments[$argumentKey] = $newArgumentValue;
                $matchedHost = $instance['tag'];
                break;
            }

        }

    }

}

/*
 * Return processed arguments
 */
echo "export ec2args=" . escapeshellarg(implode(' ', $arguments)) . ";\n";
echo "export ec2host=" . $matchedHost . ";\n";
