var fs = require('fs');
var logger = require('./log');
var nconf = require('nconf');
var conf_file = './config/config.json';
var db = require('./knex/knex.js');
nconf.file({file: conf_file});
nconf.load();

// initialize the database if it does not already exist
function init(release) {
    var dbtype = nconf.get('database:type')
    //This is here for compatibility with old versions. Will set the DB type then exit. 
    if (dbtype == null || dbtype == 'sqlite') {
        nconf.set('database:type', 'sqlite3');
        nconf.set('database:file', './messages.db');
        nconf.save()
        logger.main.error('Error reading database type. Defaulting to SQLITE3. Killing application')
        process.exit(1)
    }
    //legacy compatibility for SQLITE3 i don't like this at all :\
    if (dbtype == 'sqlite3') {
        db.raw(`pragma user_version;`).then(function (res) {
            logger.main.info("Current DB version: " + res[0].user_version);
            if (res[0].user_version < 20181118 && res[0].user_version != 0) {
                logger.main.error("Unsupported Upgrade Version - Upgrade Pagermon Database to v0.2.3 BEFORE upgrading to v0.3.0");
                process.exit(1)
            } else if (res[0].user_version == 20181118) {
                logger.main.info('Manually marking database migrations as complete')
                //This code manually marks migrations complete for existing databases, prevents errors on startup for existing DB's 
                Promise.all([
                db('knex_migrations')
                    .insert({id:1},{name: '20190322204646_create_capcodes_table.js'},{migration_time: moment().unix()})
                    .then((result) => { 
                        logger.main.debug('Marking migration 1 as complete for existing database')
                    })
                    .catch ((err) => {
                        logger.main.error('Error marking migration 1 as complete for existing database')
                    }),
                db('knex_migrations')
                    .insert({id:2},{name: '20190322204706_create_messages_table.js'},{migration_time: moment().unix()})
                    .then((result) => { 
                        logger.main.debug('Marking migration 2 as complete for existing database')
                    })
                    .catch ((err) => {
                        logger.main.error('Error marking migration 2 as complete for existing database')
                    }),
                db('knex_migrations')
                    .insert({id:3},{name: '20190322204710_create_indexes_triggers.js'},{migration_time: moment().unix()})
                    .then((result) => {
                        logger.main.debug('Marking migration 3 as complete for existing database')
                    })
                    .catch ((err) => {
                        logger.main.error('Error marking migration 3 as complete for existing database')
                    })
                ])
                .then ((result) => {
                    var vervar = 'pragma user_version = ' + release + ';'
                    db.raw(vervar)
                })
                .catch ((err) => {
                    logger.main.error('Failed to upgrade database')
                })
            } else {
                logger.main.info('Checking for database upgrades')
                db.migrate.latest()
                .then((result) => {
                    var vervar = 'pragma user_version = ' + release + ';'
                    db.raw(vervar)
                })
                .catch((err) => {
                    logger.main.error(err)
                })
            }
        })
    } else {
        db.migrate.latest()
        .then((result) => {
        })
        .catch((err) => {
            logger.main.error(err)
        })
    }
}

module.exports = {
    init: init
}

@@ -44,24 +44,56 @@
 e('./log');%0A
+var moment = require('moment');%0A
 var nconf = 
@@ -1518,96 +1518,320 @@
     
-Promise.all(%5B%0A                db('knex_migrations')%0A                    .insert(%7Bid:1%7D,%7B
+var datetime = moment().unix()%0A                var migration1 = %7Bid:1,name: '20190322204646_create_capcodes_table.js',batch:1,migration_time: datetime%7D%0A                var migration2 = %7Bid:2,name: '20190322204706_create_messages_table.js',batch:1,migration_time: datetime%7D%0A                var migration3 = %7Bid:3,
 name
@@ -1840,35 +1840,35 @@
 '20190322204
-646
+710
 _create_
 capcodes_tab
@@ -1859,61 +1859,169 @@
 ate_
-capcodes_table.js'%7D,%7Bmigration_time: moment().unix()%7D
+indexes_triggers.js',batch:1,migration_time: datetime%7D%0A                Promise.all(%5B%0A                db('knex_migrations')%0A                    .insert(migration1
 )%0A  
@@ -2419,98 +2419,18 @@
 ert(
-%7Bid:2%7D,%7Bname: '20190322204706_create_messages_table.js'%7D,%7Bmigration_time: moment().unix()%7D
+migration2
 )%0A  
@@ -2828,100 +2828,18 @@
 ert(
-%7Bid:3%7D,%7Bname: '20190322204710_create_indexes_triggers.js'%7D,%7Bmigration_time: moment().unix()%7D
+migration3
 )%0A  
@@ -3322,32 +3322,310 @@
  db.raw(vervar)%0A
+                    .then((result) =%3E %7B%0A                        logger.main.info('Setting DB to version: ' + release)%0A                    %7D)%0A                    .catch((err) =%3E %7B%0A                        logger.main.error('Error setting DB Version' + err)%0A                    %7D)%0A
                 

Fix migration hackery for current version upgrades