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

/*
 * Copyright (c) 2014 Toha <tohenk@yahoo.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do
 * so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

$sources = array(
    'mysql.com' => array('url' => 'http://dev.mysql.com/doc/mysqld-version-reference/en/mysqld-version-reference-reservedwords-5-7.html', 'xpath' => '//code[@class="literal"]'),
    'drupal.org' => array('url' => 'https://www.drupal.org/node/141051', 'xpath' => '//ol/li'),
    'db.apache.org' => array('url' => 'https://db.apache.org/derby/docs/10.1/ref/rrefkeywords29722.html', 'xpath' => '//ul[@class="simple"]/li'),
);

$i = 0;
echo "Update SQL reserved words from:\n";
foreach ($sources as $site => $data) {
    $i++;
    echo sprintf("%2d. %s\n", $i, $site);
}
$choice = 1;
while (true) {
    while (true) {
        echo sprintf("Enter choice [%s]? ", (string) $choice);
        $input = trim(fgets(STDIN));
        if (0 == strlen($input)) {
            break;
        }
        if (is_numeric($input)) {
            $choice = (int) $input;
            break;
        }
    }
    if ($choice > 0 && $choice <= count($sources)) {
        break;
    }
}
$keys = array_keys($sources);
$source = $keys[$choice - 1];

echo "\nUpdating from $source\n";

// get remote content
$file = null;
$url = $sources[$source]['url'];
if (ini_get('allow_url_fopen')) {
    $file = file_get_contents($url);
} elseif (extension_loaded('curl')) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
    $file = curl_exec($ch);
    curl_close($ch);
}

if (null === $file || false === $file) {
    echo "Can't fetch $url, aborting...\n";
    exit(1);
} else {
    echo sprintf("Retrieved %d bytes\n", strlen($file));
}

// parse content
if (false === ($doc = @DOMDocument::loadHTML($file))) {
    echo "Retrieved content is not valid HTML, aborting...\n";
    exit(1);
}
$xpath = new DOMXPath($doc);
$nodes = $xpath->query($sources[$source]['xpath']);
if (!count($nodes))
{
    echo "No match found, aborting...\n";
    exit(1);
}
$words = array();
foreach ($nodes as $node) {
    $w = strtoupper((string) $node->nodeValue);
    if (in_array($w, $words)) {
        echo sprintf("Duplicate: %s\n", $w);
    } else {
        echo sprintf("Found: %s\n", $w);
        $words[] = $w;
    }
}
if (!count($words)) {
    echo "No reserved words found, aborting...\n";
    exit(1);
}

// build reserved words
echo sprintf("Found %d reserved words.\n", count($words));
$lines = array();
$line = null;
$indent = str_repeat(' ', 8);
$maxline = 80;
while (true) {
    $w = array_shift($words);
    $w = var_export($w, true);
    if (null === $line) {
        $line = $indent;
    }
    $line .= $w.', ';
    if (strlen(rtrim($line)) >= $maxline || empty($words)) {
        $lines[] = rtrim($line);
        $line = null;
    }
    if (empty($words)) {
        break;
    }
}

// update template
$template = file_get_contents(__DIR__.'/ReservedWords.php.template');
$template = strtr($template, array(
    '//%GENERATED_BY%//' => basename(__FILE__),
    '//%GENERATED_AT%//' => date('Y-m-d H:i:s'),
    '//%URL%//' => $url,
    '//%WORDS%//' => trim(implode("\n", $lines)),
));
file_put_contents(__DIR__.'/../lib/MwbExporter/Helper/ReservedWords.php', $template);

echo "All done.\n\n";
