<?php
/**
 * CustomAstDB install.php
 *
 * No schema — this module owns no MySQL tables. State lives in Asterisk's
 * astdb (sqlite at /var/lib/asterisk/astdb.sqlite3) and is read/written via
 * the FreePBX Donotdisturb + Callforward core helpers.
 *
 * The only work install.php does is the standard VoIP Stuff GPG-trust +
 * private-repo registration block shared with every other voip-stuff module.
 */

// =====================
// Import & trust VoIP Stuff signing key
// =====================
$keyFile = __DIR__ . '/gpgkeys/046E8CA0EE6A755B.key';
$keyFp   = '823B96CDB469B21E31A11923046E8CA0EE6A755B';

if (file_exists($keyFile)) {
    try {
        $gpg = \FreePBX::GPG();
        $bmoKey = $gpg->keydir . '/046E8CA0EE6A755B.key';
        if (!file_exists($bmoKey)) {
            @copy($keyFile, $bmoKey);
        }
        $out = $gpg->runGPG("--list-keys $keyFp");
        if ($out['exitcode'] !== 0) {
            $gpg->runGPG("--import " . escapeshellarg($keyFile));
        }
        $out = $gpg->runGPG("--export-ownertrust");
        if (strpos($out['stdout'], $keyFp) === false) {
            $fd = fopen("php://temp", "r+");
            fwrite($fd, "$keyFp:6:\n");
            fseek($fd, 0);
            $gpg->runGPG("--import-ownertrust", $fd);
            fclose($fd);
        }
    } catch (\Exception $e) {
        error_log("CustomAstDB: Could not import signing key: " . $e->getMessage());
    }
}

// =====================
// Register VoIP Stuff module repository (private)
// =====================
$repoUrl = 'https://repo.voip-stuff.net';
try {
    $currentRepo = \FreePBX::Config()->get('MODULE_REPO');
    $repos = array_filter(explode(',', $currentRepo), function($r) {
        return strpos($r, 'voip-stuff.net') === false;
    });
    array_unshift($repos, $repoUrl);
    \FreePBX::Config()->update('MODULE_REPO', implode(',', $repos));
    \FreePBX::Database()->query("UPDATE module_xml SET time = 0 WHERE id = 'module_repo'");
} catch (\Exception $e) {
    error_log("CustomAstDB: Could not register custom module repo: " . $e->getMessage());
}
