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

/*
 * This file is part of ScientiaMobile WURFL PHP API
 *
 * (c) ScientiaMobile, Inc. http://www.scientiamobile.com
 *
 * This software package is the property of ScientiaMobile Inc. and is licensed commercially according to a contract
 * between the Licensee and ScientiaMobile Inc. (Licensor).
 * If you represent the Licensee, please refer to the licensing agreement which has been signed between the two parties.
 * If you do not represent the Licensee, you are not authorized to use this software in any way.
 */

if (!ini_get('date.timezone')) {
    ini_set('date.timezone', 'UTC');
}

ini_set('display_errors', 'on');

error_reporting(E_ALL);

define("WURFL_ROOT_DIR", realpath(__DIR__));

foreach ([__DIR__ . '/../../autoload.php', __DIR__ . '/vendor/autoload.php'] as $index => $file) {
    if (file_exists($file)) {
        define('WURFL_COMPOSER_INSTALL', $file);
        break;
    }
}

unset($file);

if (!defined('WURFL_COMPOSER_INSTALL')) {
    fwrite(STDERR,
        'You need to set up the WURFL dependencies using the following commands:' . PHP_EOL .
        'wget http://getcomposer.org/composer.phar' . PHP_EOL .
        'php composer.phar install' . PHP_EOL
    );

    exit(1);
}

require WURFL_COMPOSER_INSTALL;

$short_options = '';
$short_options .= 'c:';
$short_options .= 'h';

$long_options = [
    'configuration:',
    'help',
    'force::',
    'proxy:',
    'clear-cache::',
];

$options = getopt($short_options, $long_options);

if (isset($options['help']) || isset($options['h']) || !isset($options['c'])) {
    $api_version = \ScientiaMobile\WURFL\Api::getVersion();
    $usage = <<<EOL

ScientiaMobile WURFL PHP API $api_version
CLI Updater
---------------------------------------
Usage: php wurfl-updater [OPTIONS]

Option                        Meaning
 -c <file>                    Specify the configuration file. Ex. config/config.php.example
 --force                      Force an update even if the WURFL data is up to date
 --proxy                      Use the specified proxy server address. Ex. proxy.example.com:5100
 --clear-cache                Clear the cache
 -h|--help                    Show this message


EOL;

    print $usage;
    exit;
}

if (isset($options['c'])) {
    $config_file = $options['c'];
    if (!file_exists($config_file)) {
        fwrite(STDERR,
            sprintf('Could not read "%s".', $config_file) . PHP_EOL
        );
        exit(1);
    }
}

$force_update = false;
if (isset($options['force'])) {
    $force_update = true;
}

$proxy = false;
if (isset($options['proxy'])) {
    $proxy = $options['proxy'];
}

$clear_cache = false;
if (isset($options['clear-cache'])) {
    $clear_cache = true;
}

try {
    /**
     * @var \ScientiaMobile\WURFL\Container\Container $container
     */
    $container = require $config_file;

    $container->set('proxy', function() use ($proxy) {
        return $proxy;
    });

    $logger = $container->get('logger');
    if ($logger instanceof \Psr\Log\NullLogger) {
        $logger = new \ScientiaMobile\WURFL\Logger\ConsoleLogger();
        $container->setLogger($logger);
    }

    $settings = $container->get('settings');
    $storage_path = $settings['wurfl_storage_path'];

    if ($storage_path === \ScientiaMobile\WURFL\Utils\File::getDefaultStoragePath()) {
        $logger->warning('');
        $logger->warning('WARNING: This configuration is using the default setting for the storage path: ' . $storage_path);
        $logger->warning('         Please specify a value for "wurfl_storage_path" in the configuration file, ');
        $logger->warning('         since data saved in the default storage path could be removed on APIs upgrade.');
        $logger->warning('');
    }

    \ScientiaMobile\WURFL\Utils\File::createDirIfNotExist($storage_path);

    if ($force_update) {
        \ScientiaMobile\WURFL\Repositories\RepositoryManager::forceUpdate($container);
    } else {
        \ScientiaMobile\WURFL\Repositories\RepositoryManager::update($container);
    }

    if ($clear_cache) {
        $logger->info('');
        $logger->info('Clearing cache...');
        $container->get('cache')->clear();
        $logger->info('All cache cleared.');
        $logger->info('');
    }

} catch (\ScientiaMobile\WURFL\Exceptions\WURFLException $we) {
    print 'Exception: ' . $we->getMessage() . PHP_EOL;
    exit(1);
}
