<?php

/**
 * Twig extension to make AWS Instance-Id visible in templates
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2015 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace Sso\Tools\AWSBundle\Twig\Extension;

use GuzzleHttp\Client;
use Psr\Cache\InvalidArgumentException;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Contracts\Cache\CacheInterface;
use Twig\Extension\AbstractExtension;
use Twig\Extension\GlobalsInterface;

/**
 * Class AWS
 *
 * @copyright  2016 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 * @package Sso\Tools\AWSBundle\Twig\Extension
 */
class AwsExtension extends AbstractExtension implements GlobalsInterface
{
    const SERVICE_URL = 'http://169.254.169.254/latest/meta-data/instance-id';
    const CACHE_NAMESPACE = 'aws';
    const CACHE_ID = 'instance-id';
    const CACHE_LIFETIME = 7200;

    /**
     * @var CacheInterface|null
     */
    private $cache;

    /**
     * @var string
     */
    private $awsInstanceId;

    /**
     * AWS constructor.
     */
    public function __construct()
    {
        $this->cache = new FilesystemAdapter(static::CACHE_NAMESPACE, static::CACHE_LIFETIME);
    }

    /**
     * Get global variables
     *
     * @return array
     */
    public function getGlobals()
    {
        return array(
            'awsInstanceId' => $this->getAwsInstanceId()
        );
    }

    /**
     * Get aws instance id
     *
     * @return string
     */
    public function getAwsInstanceId(): string
    {
        if (false === getenv('APP_LOGS')) {
            return '';
        }

        if (null === $this->awsInstanceId) {
            try {
                $this->awsInstanceId = $this->cache->get(static::CACHE_ID, function () {
                    $options = [
                        'connect_timeout' => 5,
                        'timeout' => 7,
                    ];
                    try {
                        return (string)(new Client())->get(static::SERVICE_URL, $options)->getBody()->getContents();
                    } catch (\Exception $exception) {
                        return 'id-failed-service';
                    }
                });
            } catch (InvalidArgumentException $exception) {
                $this->awsInstanceId = 'id-failed-cache';
            }
        }

        return $this->awsInstanceId;
    }
}
