#!/usr/bin/env node

const { lstatSync, readdirSync,readFileSync } = require('fs')
const fs = require('fs')
const { join,resolve } = require('path')
const {spawnSync} = require('child_process')
const os = require('os')
const mysql      = require('mysql');
var connection = null;
var allSqls = [];

let cwd = process.cwd();

const isDirectory = source => lstatSync(source).isDirectory()
const getDirectories = source =>
    readdirSync(resolve(cwd, source)).map(name => join(source, name)).filter(isDirectory)

const isAppDir = function (dir) {
    try {
        return fs.existsSync(join(dir, 'sql','createTables.sql'))
    } catch (e) {
        return false
    }
}


function execSqls(sqls, idx){
    let sql = sqls[idx];
    sql = sql.trim();
    if(!sql){
        console.log(idx + " empty line.");
        if(idx < sqls.length-1){
            execSqls(sqls,idx+1);
            return;
        }
    }
    else{
        connection.query(sql,function(error, results, fields){
            if (error){
                console.log(idx +" failed " + sql );
                console.log(error.sqlMessage);
                /*if(idx < sqls.length-1){
                    execSqls(sqls,idx+1);
                }*/
            }
            else{
                console.log(" 成功执行 " + idx);
                if(idx < sqls.length-1){
                    execSqls(sqls,idx+1);
                }
            }

        });
    }

}

function buildAppDir (dir) {
    let content = readFileSync(resolve(dir,"sql/createTables.sql"), {encoding: 'utf-8'});
    let sqls = content.split(";");
    allSqls = allSqls.concat(sqls);
}

function buildDir(d){
    console.log("processing " + d);
    if(isAppDir(d)){
        buildAppDir(d);
    }else{
        var dirs = getDirectories(d);
        dirs.map(dir=>{
            var fulldir = resolve(d,dir);
            buildDir(fulldir);
        });
    }
}

var configFile = resolve(cwd,"owlconfig.json");

if(process.argv.length>2){
    configFile = resolve(cwd, process.argv[2]);
}

var content = readFileSync(configFile, {encoding: 'utf-8'})
var owlconfig = JSON.parse(content)

connection = mysql.createConnection(owlconfig.mysql);


var full = resolve(cwd,owlconfig.generatedApps);
buildDir(full);
console.log("collect all sqls, total=" + allSqls.length);
execSqls(allSqls,0);


