'use strict';

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

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

        // keep the paths around, so that we don't need to trigger a re-configure. the old nginx config will use the paths
        // the new one will proxy calls to the box code
        const WELLKNOWN_DIR = '/home/yellowtent/boxdata/well-known';
        const output = safe.child_process.execSync('find . -type f -printf "%P\n"', { cwd: WELLKNOWN_DIR, encoding: 'utf8' });
        if (!output) return callback();
        const paths = output.trim().split('\n');
        if (paths.length === 0) return callback(); // user didn't configure any well-known

        let wellKnown = {};
        for (let path of paths) {
            const fqdn = path.split('/', 1)[0];
            const loc = path.slice(fqdn.length+1);
            const doc = safe.fs.readFileSync(`${WELLKNOWN_DIR}/${path}`, { encoding: 'utf8' });
            if (!doc) continue;

            wellKnown[fqdn] = {};
            wellKnown[fqdn][loc] = doc;
        }

        console.log('Migrating well-known', JSON.stringify(wellKnown, null, 4));

        async.eachSeries(Object.keys(wellKnown), function (fqdn, iteratorDone) {
            db.runSql('UPDATE domains SET wellKnownJson=? WHERE domain=?', [ JSON.stringify(wellKnown[fqdn]), fqdn ], function (error, result) {
                if (error) {
                    console.error(error); // maybe the domain does not exist anymore
                } else if (result.affectedRows === 0) {
                    console.log(`Could not migrate wellknown as domain ${fqdn} is missing`);
                }
                iteratorDone();
            });
        }, function (error) {
            callback(error);
        });
    });
};

exports.down = function(db, callback) {
    db.runSql('ALTER TABLE domains DROP COLUMN wellKnownJson', function (error) {
        if (error) console.error(error);
        callback(error);
    });
};
