'use strict';

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

const CERTS_DIR = '/home/yellowtent/boxdata/certs';

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

        db.all('SELECT * FROM subdomains', [ ], function (error, subdomains) {
            if (error) return callback(error);

            async.eachSeries(subdomains, function (subdomain, iteratorDone) {
                const cert = safe.fs.readFileSync(`${CERTS_DIR}/${subdomain.subdomain}.${subdomain.domain}.user.cert`, 'utf8');
                const key = safe.fs.readFileSync(`${CERTS_DIR}/${subdomain.subdomain}.${subdomain.domain}.user.key`, 'utf8');

                if (!cert || !key) return iteratorDone();

                const certificate = { cert, key };

                db.runSql('UPDATE subdomains SET certificateJson=? WHERE domain=? AND subdomain=?', [ JSON.stringify(certificate), subdomain.domain, subdomain.subdomain ], iteratorDone);
            }, callback);
        });
    });
};

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