/**
 * Clean a directory.
 * @function ci.worker.cleanDirectory
 * @param {object} config - Work configuration.
 * @param {string} config.dir - Directory to clean. Can be a glob pattern.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 */
var path = require('path'),
    debug = require('./_debug'),
    file = require('../../lib/file'),
    expandGlob = file.expandGlob,
    rmdirRecursive = file.rmdirRecursive;

module.exports = function (config, callback) {
    var baseDir = config.dir;
    expandGlob(baseDir, function (err, dirnames) {
        if (err) {
            callback(err);
            return;
        }
        var async = require('async');
        async.series(
            dirnames
                .map(function (dirname) {
                    return path.resolve(baseDir, dirname)
                })
                .map(function (dirname) {
                    return function (callback) {
                        rmdirRecursive(dirname, function (err) {
                            if (!err) {
                                debug('Clean directory:%s', dirname);
                            }
                            callback(err);
                        });
                    }
                }),
            function (err) {
                callback(err);
            }
        )
    });
};