#!/usr/bin/php
<?php
/*
* Load json and convert it to PHP object:
*/
$devices = var_export(
    json_decode(
        file_get_contents(
            'https://raw.githubusercontent.com/opawg/user-agents-v2/master/src/devices.json'
        ),
        true
    ),
    true
);
$bots = var_export(
    json_decode(
        file_get_contents(
            'https://raw.githubusercontent.com/opawg/user-agents-v2/master/src/bots.json'
        ),
        true
    ),
    true
);
$apps = var_export(
    json_decode(
        file_get_contents(
            'https://raw.githubusercontent.com/opawg/user-agents-v2/master/src/apps.json'
        ),
        true
    ),
    true
);
$libraries = var_export(
    json_decode(
        file_get_contents(
            'https://raw.githubusercontent.com/opawg/user-agents-v2/master/src/libraries.json'
        ),
        true
    ),
    true
);
$browsers = var_export(
    json_decode(
        file_get_contents(
            'https://raw.githubusercontent.com/opawg/user-agents-v2/master/src/browsers.json'
        ),
        true
    ),
    true
);


// autogenerate database
print <<<EOT
<?php
namespace Opawg\UserAgentsV2Php;

/* Autogenerated.  Do not edit */
 
class UserAgents {
    public static function find(\$currentUserAgent)
    {
        \$playerFound = null;
        \$deviceFound = '';

        //Search for device:
        foreach (self::\$devices['entries'] as \$device) {
            //Does the HTTP_USER_AGENT match this regexp:
            if (preg_match("#{\$device['pattern']}#", \$currentUserAgent)) {
                \$deviceFound = \$device['name'];
                //We found it!
                break 1;
            }
        }
        //Search for current HTTP_USER_AGENT:
        foreach (self::\$db as \$type => \$userAgents) {
            foreach (\$userAgents['entries'] as \$userAgent) {
                //Does the HTTP_USER_AGENT match this regexp:
                if (preg_match("#{\$userAgent['pattern']}#", \$currentUserAgent)) {
                    \$playerFound = [
                        'app' => \$userAgent['name'],
                        'device' => \$deviceFound,
                        'os' => '',
                        'bot' => (\$type=='bots') ? \$userAgent['name'] : 0,
                    ];
                    //We found it!
                    break 2;
                }
            }
        }
        return \$playerFound;
    }


EOT;
print "    static public \$devices = ";
print $devices;
print ";\n";

print "    static public \$db = array(\n";
print "    'bots' => \n";
print $bots;
print "    ,\n";

print "    'apps' => \n";
print $apps;
print "    ,\n";

print "    'libraries' => \n";
print $libraries;
print "    ,\n";

print "    'browsers' => \n";
print $browsers;
print "\n    );\n";

print "}\n";

