#! /usr/bin/env node

var Fashion = null,
    fs = require('fs'),
    path = require('path'),
    cwd = path.resolve('.'),
    cwdWas, fashionJs, mondoPath, mondoDir, mondo;

// start in current directory looking for locally installed node modules

while (cwd && cwd !== '/') {
    fashionJs = path.resolve(cwd, "node_modules/fashion/fashion.js");
    mondoPath = path.resolve(cwd, 'node_modules/mondorepo');
    if (fs.existsSync(fashionJs)) {
        Fashion = require(fashionJs);
        break;
    }
    else if (fs.existsSync(mondoPath)) {
        mondoDir = mondoPath;
    }
    cwdWas = cwd;
    cwd = path.dirname(cwd);
    if (cwd == cwdWas) {
        cwd = null;
    }
}

if (!Fashion && mondoDir) {
    var mondo = require(mondoDir),
        repo = mondo.Repo.open(process.cwd()),
        packages = repo.visiblePackages;
    
    if (packages) {
        for (var pkg of packages) {
            if (pkg.name === 'fashion') {
                Fashion = require(path.resolve(pkg.path, "fashion.js"));
                break;
            }
        }
    }
}

var testPaths = [
        path.resolve(__dirname, "../fashion.js"),
        path.resolve(__dirname, "./fashion.js"),
        "fashion/fashion.js",
    ];

while (!Fashion && testPaths.length) {
    try {
        var testPath = testPaths.shift();
        Fashion = require(testPath);
    }
    catch (err) {
        continue;
    }
}

if (!Fashion) {
    throw new Error("Unable to locate fashion/fashion.js module");
}
