'use strict';

const fs = require('node:fs'),
    hush = require('../src/hush.js').default;

exports.up = function(db, callback) {
    db.all('SELECT value FROM settings WHERE name="backup_config"', function (error, results) {
        if (error || results.length === 0) return callback(error);

        var backupConfig = JSON.parse(results[0].value);
        if (backupConfig.key) {
            backupConfig.encryption = hush.generateEncryptionKeysSync(backupConfig.key);
            // backupSites.cleanupCacheFilesSync();

            fs.writeFileSync('/home/yellowtent/platformdata/BACKUP_PASSWORD',
                'This file contains your Cloudron backup password.\nBefore Cloudron v5.2, this was saved in the database.' +
                'From Cloudron 5.2, this password is not required anymore. We generate strong keys based off this password and use those keys to encrypt the backups.\n' +
                'This means that the password is only required at decryption/restore time.\n\n' +
                'This file can be safely removed and only exists for the off-chance that you do not remember your backup password.\n\n' +
                `Password: ${backupConfig.key}\n`,
                'utf8');

        } else {
            backupConfig.encryption = null;
        }

        delete backupConfig.key;

        db.runSql('UPDATE settings SET value=? WHERE name="backup_config"', [ JSON.stringify(backupConfig) ], callback);
    });
};

exports.down = function(db, callback) {
    callback();
};
