'use strict';

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

const OLD_CERTS_DIR = '/home/yellowtent/boxdata/certs';
const NEW_CERTS_DIR = '/home/yellowtent/platformdata/nginx/cert';

exports.up = function(db, callback) {
    fs.readdir(OLD_CERTS_DIR, function (error, filenames) {
        if (error && error.code === 'ENOENT') return callback();
        if (error) return callback(error);

        filenames = filenames.filter(f => f.endsWith('.key') && !f.endsWith('.host.key') && !f.endsWith('.user.key')); // ignore fallback and user keys

        async.eachSeries(filenames, function (filename, iteratorCallback) {
            const privateKeyFile = filename;
            const privateKey = fs.readFileSync(path.join(OLD_CERTS_DIR, filename));
            const certificateFile = filename.replace(/\.key$/, '.cert');
            const certificate = safe.fs.readFileSync(path.join(OLD_CERTS_DIR, certificateFile));
            if (!certificate) {
                console.log(`${certificateFile} is missing. skipping migration`);
                return iteratorCallback();
            }
            const csrFile = filename.replace(/\.key$/, '.csr');
            const csr = safe.fs.readFileSync(path.join(OLD_CERTS_DIR, csrFile));
            if (!csr) {
                console.log(`${csrFile} is missing. skipping migration`);
                return iteratorCallback();
            }

            async.series([
                db.runSql.bind(db, 'INSERT INTO blobs (id, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value=VALUES(value)', `cert-${privateKeyFile}`, privateKey),
                db.runSql.bind(db, 'INSERT INTO blobs (id, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value=VALUES(value)', `cert-${certificateFile}`, certificate),
                db.runSql.bind(db, 'INSERT INTO blobs (id, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value=VALUES(value)', `cert-${csrFile}`, csr),
            ], iteratorCallback);
        }, function (error) {
            if (error) return callback(error);

            child_process.execSync(`cp ${OLD_CERTS_DIR}/* ${NEW_CERTS_DIR}`); // this way we copy the non-migrated ones like .host, .user etc as well
            fs.rm(OLD_CERTS_DIR, { recursive: true }, callback);
        });
    });
};

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

