
var myArgs = process.argv.slice(2);

if ( myArgs.length < 1 ) {
    console.log("Missing args", myArgs);
    process.exit(0);
}
console.log("myArgs", myArgs);
const ISODATE = new Date(myArgs[0]).toISOString();

const db = require('qmi-cloud-common/mongo');
const fs = require('fs-extra');

async function asyncForEach(array, callback) {
    for (let index = 0; index < array.length; index++) {
        await callback(array[index], index, array);
    }
}

async function init() {
    let provisions = await db.provision.get({
        "isDestroyed":true, 
        "isDeleted": false,
        "created": { "$lt" : ISODATE }
    });
    await asyncForEach(provisions.results, async function(p)  {
        await doMoveDestroyed(p);
    });
}

const doMoveDestroyed = async function(provision) {
    var scenarioFolder = `${provision.scenario}_${provision._id}`;
    console.log(`Moving scenario: /provisions/${scenarioFolder}`);
    if (fs.existsSync(`/provisions/${scenarioFolder}`)) {
        fs.moveSync(`/provisions/${scenarioFolder}`, `/provisions/deleted/${scenarioFolder}`, { overwrite: true })
        console.log(`OK.`);
    } else {
        console.log(`NOK: It does not exist.`);
    }
    
};

function check() {
    init().then(function(){
        db.mongoose.connection.close()
        process.exit(0);
        
    }).catch(function(e){
        db.mongoose.connection.close()
        console.log("Error", e);
        process.exit(0);
    });
}


// --------------------------------
check();




