<?php
/**
 * api: cli
 * title: Rehash plain password
 * description: Looks for unhashed password literals, and calculates hash
 * version: 0.1
 * category: postprocessing
 * type: cron
 * x-cron: 9,17 20 * * *
 *
 * Fix for unhashed passwords.
 *
 */

chdir(dirname(__DIR__)); 
include("config.php");

/**
 * Scan each project,
 * split up `tags` as CSV and just fille up according tags table.
 *
 */
db("BEGIN IMMEDIATE TRANSACTION");
foreach (db("SELECT name, lock, MAX(t_changed) FROM release_versions GROUP BY name")->fetchAll() as $entry) {

    extract($entry);
    if (strlen(trim($lock))) {
        $tokens = p_csv($entry["lock"]);
        $updated = false;
        
        # find plain passwords
        foreach ($tokens as $i=>$pw) {
            if (strpos($pw, "://")) {
                continue;
            }
            elseif (strncmp($pw, '$2y$10$', 7) == 0) {
                continue;
            }
            else {
                $updated = 1;
                $tokens[$i] = password_hash($pw, PASSWORD_DEFAULT);
                print " ↓ $pw → $tokens[$i]\n";
            }
        }
        
        # update record
        if ($updated and $tokens) {
            $r = new release($name);
            $r->update(
                ["lock" => join(", ", $tokens)],
                [], [], TRUE
            );
            $r->store();
            #print_r($r);
            print "Hashin password for `$name`\n";
        }
    }
}
db("END TRANSACTION");

