'use strict';

const async = require('async'),
    safe = require('safetydance');

const CERTS_DIR = '/home/yellowtent/boxdata/certs',
    PLATFORM_CERTS_DIR = '/home/yellowtent/platformdata/nginx/cert';

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

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

            async.eachSeries(domains, function (domain, iteratorDone) {
                // b94dbf5fa33a6d68d784571721ff44348c2d88aa seems to have moved certs from platformdata to boxdata
                let cert = safe.fs.readFileSync(`${CERTS_DIR}/${domain.domain}.host.cert`, 'utf8');
                let key = safe.fs.readFileSync(`${CERTS_DIR}/${domain.domain}.host.key`, 'utf8');

                if (!cert) {
                    cert = safe.fs.readFileSync(`${PLATFORM_CERTS_DIR}/${domain.domain}.host.cert`, 'utf8');
                    key = safe.fs.readFileSync(`${PLATFORM_CERTS_DIR}/${domain.domain}.host.key`, 'utf8');
                }

                const fallbackCertificate = { cert, key };

                db.runSql('UPDATE domains SET fallbackCertificateJson=? WHERE domain=?', [ JSON.stringify(fallbackCertificate), domain.domain ], iteratorDone);
            }, callback);
        });
    });
};

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