'use strict';

const async = require('async'),
    fs = require('node:fs'),
    path = require('node:path'),
    safe = require('safetydance');

const MAIL_DATA_DIR = '/home/yellowtent/boxdata/mail';
const DKIM_DIR = `${MAIL_DATA_DIR}/dkim`;

exports.up = function(db, callback) {
    db.runSql('ALTER TABLE mail ADD COLUMN dkimKeyJson MEDIUMTEXT', function (error) {
        if (error) return callback(error);

        fs.readdir(DKIM_DIR, function (error, filenames) {
            if (error && error.code === 'ENOENT') return callback();
            if (error) return callback(error);

            async.eachSeries(filenames, function (filename, iteratorCallback) {
                const domain = filename;
                const publicKey = safe.fs.readFileSync(path.join(DKIM_DIR, domain, 'public'), 'utf8');
                const privateKey = safe.fs.readFileSync(path.join(DKIM_DIR, domain, 'private'), 'utf8');
                if (!publicKey || !privateKey) return iteratorCallback();

                const dkimKey = {
                    publicKey,
                    privateKey
                };

                db.runSql('UPDATE mail SET dkimKeyJson=? WHERE domain=?', [ JSON.stringify(dkimKey), domain ], iteratorCallback);
            }, function (error) {
                if (error) return callback(error);

                fs.rm(DKIM_DIR, { recursive: true }, callback);
            });
        });
    });
};

exports.down = function(db, callback) {
    async.series([
        db.runSql.run(db, 'ALTER TABLE mail DROP COLUMN dkimKeyJson')
    ], callback);
};
