const mysql = require('mysql2/promise');
const fs = require('fs-extra');

(async () => {
    try {
        const connection = await mysql.createConnection({
            host: 'localhost',
            user: 'root',
            multipleStatements: true
        });
        let changesDir = './install/changes';
        let results = await connection.query("SELECT dbVersion FROM util.config");
        if (results[0].length != 1)
            throw new Error('There must be exactly one row in the configuration table');
        let version = results[0][0].dbVersion;
        if (!version)
            throw new Error('Database version not defined');
        let dirs = await fs.readdir(changesDir);
        dirs.sort(compareVersions);
        let lastVersion;

        for (let dir of dirs) {
            if (compareVersions(dir, version) <= 0) continue;
            if (/^\./.test(dir)) continue;
            let path = `${changesDir}/${dir}`;
            let files = await fs.readdir(path);
            files.sort();
            console.log(dir);
            for (let file of files) {
                let sql = await fs.readFile(`${path}/${file}`, 'utf8');
                if (/^\s*$/.test(sql)) continue;
                await connection.query(sql);
                console.log(` - ${file}`);
            }
            lastVersion = dir;
        }
        if (lastVersion) {
            await connection.query("UPDATE util.config SET dbVersion = ?", [lastVersion]);
            console.log(`Database upgraded successfully to version ${lastVersion}`);
        } else {
            console.log("Database is alredy in the last version");
        }
        await connection.end();
        process.exit();
    } catch (err) {
        console.error(err);
        process.exit(1);
    }
})();

function compareVersions(ver1, ver2) {
    let diff;
    ver1 = ver1.split('.');
    ver2 = ver2.split('.');

    diff = parseInt(ver1[0]) - parseInt(ver2[0]);
    if (diff !== 0) return diff;

    diff = parseInt(ver1[1]) - parseInt(ver2[1]);
    if (diff !== 0) return diff;

    diff = parseInt(ver1[2]) - parseInt(ver2[2]);
    if (diff !== 0) return diff;

    return 0;
}