'use strict';

const async = require('async'),
    iputils = require('../src/iputils.js').default;

exports.up = function(db, callback) {
    db.runSql('ALTER TABLE apps ADD COLUMN containerIp VARCHAR(16) UNIQUE', function (error) {
        if (error) console.error(error);

        let baseIp = iputils.intFromIp('172.18.16.0');

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

            async.eachSeries(apps, function (app, iteratorDone) {
                const nextIp = iputils.ipFromInt(++baseIp);
                db.runSql('UPDATE apps SET containerIp=? WHERE id=?', [ nextIp, app.id ], iteratorDone);
            }, callback);
        });
    });
};

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

