<?php

class SettingsVCSImporter extends BaseDataImporter
{
    private $vcsConfig = '/opt/cfengine/dc-scripts/params.sh';
    private $vcsPrivateKey = '/opt/cfengine/userworkdir/admin/.ssh/id_rsa.pvt';

    public function isOnlyForAdmin(): bool
    {
        return true;
    }

    public function import($data)
    {
        $data = json_decode($data, JSON_OBJECT_AS_ARRAY);
        if (isset($data['configPath'])) {
            $content = $this->phar[$data['configPath']]->getContent();
            $content = $this->ci->cf_encrypt->decryptByKey($content, $this->encryptionKey);
            if ($content) {
                file_put_contents($this->vcsConfig, $content);
                $this->setScriptsPermissions($this->vcsConfig);
            }
        }

        if (isset($data['keyPath'])) {
            $content = $this->phar[$data['keyPath']]->getContent();
            $content = $this->ci->cf_encrypt->decryptByKey($content, $this->encryptionKey);
            if ($content) {
                file_put_contents($this->vcsPrivateKey, $content);
            }
        }

        log_audit(
            actor: $this->username,
            objectType: AUDIT_LOG_TYPE_SETTINGS,
            action: AUDIT_LOG_ACTION_UPDATE,
            objectName: AUDIT_LOG_VCS_SETTINGS_NAME,
            details: ['Updated VCS settings via Import.'],
        );
    }
}
