#!/usr/bin/php -q
<?php

/**
 * @noinspection DuplicatedCode
 */

// Debug Mode for IDE runtime debugger
define("SCRIPTDEBUG", 0);
define("DEFAULTVALUES", 0);
// is config->debug set
$GLOBALS['IS_DEBUG'] = 0;
// who was the sender
$GLOBALS['SERIAL_NUMBER'] = "UNKNOWN";

// change to web server root to load scripts
chdir("/var/www");
require_once "public/config.inc.php";
require_once "src/foundation/class.common.php";
require_once "src/class/class.globalconfig.php";
require_once "src/class/class.UUID.php";
require_once "src/foundation/db/idiorm.php";

// helpers
function writeError($id, $msg)
{
    fwrite($GLOBALS['stderr'], "ERROR: (" . $id . ") " . $msg . "\n");
}

function writeFeedback($msg)
{
    fwrite($GLOBALS['stdout'], "INFO: " . $msg . "\n");
}

function writeUsage()
{
    fwrite($GLOBALS['stdout'], "Usage: " . $GLOBALS['argv'][0] . " [fullReInit]\n");
}

function init()
{
    $oConf = new GlobalConfig('en');
    $settings = $oConf->GetParams(array(143, 179));
    $GLOBALS['SERIAL_NUMBER'] = isset($settings[143]) ? $settings[143]['str_val'] : 'UNKNOWN';
    $GLOBALS['IS_DEBUG'] = isset($settings[179]) ? intval($settings[179]['str_val']) : 0;
}

/**
 * If you use base_convert to convert a large (eg. 80-bit) hexadecimal to base-36, you might observe:
 *
 *      ABCDEF00001234567890 (hexadecimal)
 *          => 3O47RE02JZSW0KS8 (base-36)
 *          => ABCDEF00001240000000 (hexadecimal)
 *
 * This is normal and is due to the loss of precision on large numbers.
 *
 * This string-based function using the built-in BC Math Extension which will overcome this
 * and similar problems.
 *
 * @param $str
 * @param int $from_base
 * @param int $to_base
 *
 * @return int|string
 * @noinspection DuplicatedCode
 */
function str_base_convert($str, $from_base = 10, $to_base = 36)
{
    $str = trim($str);
    if (intval($from_base) != 10)
    {
        $len = strlen($str);
        $q = 0;
        for ($i = 0; $i < $len; $i++)
        {
            $r = base_convert($str[$i], $from_base, 10);
            $q = bcadd(bcmul($q, $from_base), $r);
        }
    } else $q = $str;

    if (intval($to_base) != 10)
    {
        $s = '';
        while (bccomp($q, '0', 0) > 0)
        {
            $r = intval(bcmod($q, $to_base));
            $s = base_convert($r, 10, $to_base) . $s;
            $q = bcdiv($q, $to_base, 0);
        }
    } else $s = $q;

    return $s;
}

/**
 * Use cryptic secure system calls to generate a Hex encoded random byte string
 * Upon Error throw an exception and return NULL
 *
 * @param int $length
 *
 * @return string|null
 * @throws Exception
 * @noinspection DuplicatedCode
 */
function random_token($length = 32)
{
    $bytes = null;

    if (!isset($length) || intval($length) <= 8)
    {
        $length = 32;
    }
    // php 7.0+
    if (function_exists('random_bytes'))
    {
        try
        {
            $bytes = random_bytes($length);
        } catch (Exception $e)
        {
            writeError(1, "Error randomToken->random_bytes(): " . $e->getMessage());
            $bytes = null;
        }
    }
    // 5.3+ platform dependent (apache2 & openssl)
    if (is_null($bytes) && function_exists('openssl_random_pseudo_bytes'))
    {
        $bytes = openssl_random_pseudo_bytes($length);
        if ($bytes === false)
        {
            $bytes = null;
        }
    }
    if (is_null($bytes))
    {
        throw new Exception("no cryptographically secure random function available");
    }

    return bin2hex($bytes);
}

/**
 * Load all current users and when field user_key varchar 64 is empty fill it with str_base_convert()
 * MD5 hash of our login_name
 *
 * @param string $your_user_login
 *
 * @return int|string
 * @noinspection DuplicatedCode
 */
function createTokenAPP($your_user_login = 'admin')
{
    // user_login is unique in the db
    // with more entropy result is 23 chars long
    // md5() result will be 32 chars long
    $hash = md5(uniqid($your_user_login, true));
    // only numbers and lower case characters - nearly as short as base64 encoded
    // but easier on the user when writing the token by hand
    return str_base_convert($hash, 16, 36);
}

/**
 * create a random byte value and hex encode it; add a system unique prefix to this value;
 * then compute a hash value using an old 1996 but still unbroken algorithm (RIPE MD-160);
 * then loss-less shrink the size of the string using a 36 alpha-numeric encoding base
 *
 * @param $seed string
 *
 * @return string size: about 31 bytes
 * @throws Exception
 * @noinspection DuplicatedCode
 */
function createTokenREST($seed)
{
    // create a system unique id (namespace based UUID with serial number) to improve the overall uniqueness
    $prefix = UUID::named_uuid($GLOBALS['system_uuid'], $seed);
    if ($prefix === false || empty($prefix))
    {
        $prefix = uniqid($seed, true);
    }
    $token = random_token(64); // hex encoded binary of 64 byte -> 128 bytes string
    $hash = hash("ripemd160", $prefix . '.' . $token, false); // hex encoded 40 byte hash

    // only numbers and lower case characters - nearly as short as base64 encoded
    // but easier on the user when writing the token by hand
    return str_base_convert($hash, 16, 36); // ~31 bytes string
}

function doInitialize($fullReInit = false)
{
    // initialize DB access
    /** @var siteConfig $oConf */
    $oConf = siteConfig::create();
    $dbConf = $oConf::getGroup('DB_Config');
    // access settings
    $db_name = $dbConf['database'];
    $db_user = $dbConf['user'];
    $db_pwd = $dbConf['pwd'];
    // to use a default unix socket leave host empty
    $dsn = 'pgsql:dbname=' . $db_name;
    // ORM to access the DB
    ORM::configure($dsn, null, 'initUserToken');
    ORM::configure('username', $db_user, 'initUserToken');
    ORM::configure('password', $db_pwd, 'initUserToken');
    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
    {
        ORM::configure('logging', true, 'initUserToken');
        $debugLog = function ($log_string, $query_time)
        {
            writeFeedback($log_string . ' in ' . $query_time);
        };
        ORM::configure('logger', $debugLog, 'initUserToken');
    }

    try
    {
        $fields = array(
            'id',
            'loginname',
            'user_key',
            'rest_key'
        );

        $users = ORM::for_table('users', 'initUserToken')
                    ->select_many($fields)
                    ->find_array();


        foreach ($users as $user)
        {
            $userKey = $restKey = null;
            if ($fullReInit)
            {
                $userKey = createTokenAPP($user['loginname']);
                $restKey = createTokenREST($GLOBALS['SERIAL_NUMBER']);
            } else
            {
                if (empty($user['user_key']))
                {
                    $userKey = createTokenAPP($user['loginname']);
                }
                if (empty($user['rest_key']))
                {
                    $restKey = createTokenREST($GLOBALS['SERIAL_NUMBER']);
                }
            }
            if (isset($userKey) || isset($restKey))
            {
                if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
                {
                    var_dump($user['loginname'], $userKey, $restKey);
                }

                $update = ORM::for_table('users', 'initUserToken')->find_one($user['id']);
                if ($update !== false)
                {
                    if (isset($userKey))
                    {
                        $update->set('user_key', $userKey);
                    }
                    if (isset($restKey))
                    {
                        $update->set('rest_key', $restKey);
                    }
                    $update->save();
                }
            }
        }

    } catch (Exception $e)
    {
        writeError(1, "Error doInitialize: " . $e->getMessage());
        exit(1);
    }

    return $users;
}

/**
 * main()
 *
 * @param $argc
 * @param $argv
 */
function main($argc, /** @noinspection PhpUnusedParameterInspection */
              $argv)
{
    if (SCRIPTDEBUG && DEFAULTVALUES)
    {
        doInitialize();
        exit(0);
    } else
    {
        if ($argc > 2)
        {
            writeUsage();
            writeError(2, "Wrong command line parameters");
            exit(2);
        }
        if ($argc == 2)
        {
            doInitialize(true);
        } else
        {
            doInitialize();
        }
        exit(0);
    }
}

// supported STDIN/OUT/ERR syntax for php version 4.3 till 5.3
$stderr = fopen('php://stderr', 'w');
$stdout = fopen('php://stdout', 'w');
// fetch debug flag and serial number
init();
// $argc, $argv are filled in by the CLI engine and defined as globals
main($argc, $argv);
