'use strict';

const async = require('async'),
    openssl = require('../src/openssl.js').default,
    safe = require('safetydance');

const NGINX_CERT_DIR = '/home/yellowtent/platformdata/nginx/cert';

// ensure fallbackCertificate of domains are present in database and the cert dir. it seems a bad migration lost them.
// https://forum.cloudron.io/topic/5683/data-argument-must-be-of-type-received-null-error-during-restore-process
exports.up = function(db, callback) {
    db.all('SELECT * FROM domains', [ ], function (error, domains) {
        if (error) return callback(error);

        // this code is br0ken since async 3.x since async functions won't get iteratorDone anymore
        // no point fixing this migration though since it won't run again in old cloudrons. and in new cloudron domains will be empty
        async.eachSeries(domains, async function (domain, iteratorDone) {
            let fallbackCertificate = safe.JSON.parse(domain.fallbackCertificateJson);
            if (!fallbackCertificate || !fallbackCertificate.cert || !fallbackCertificate.key) {
                let error;
                [error, fallbackCertificate] = await safe(openssl.generateCertificate(domain.domain));
                if (error) return iteratorDone(error);
            }

            if (!safe.fs.writeFileSync(`${NGINX_CERT_DIR}/${domain.domain}.host.cert`, fallbackCertificate.cert, 'utf8')) return iteratorDone(safe.error);
            if (!safe.fs.writeFileSync(`${NGINX_CERT_DIR}/${domain.domain}.host.key`, fallbackCertificate.key, 'utf8')) return iteratorDone(safe.error);

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

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