/**
 * Create a symbolic link with relative path.
 * @function lib.file.relativeSymlink
 * @param {string} src - Source file (actual file) path.
 * @param {string} dest - Destination file (link) path.
 * @param {function} callback - Callback when done.
 * @author Taka Okunishi
 *
 */
var fs = require('fs'),
    path = require('path');

module.exports = function (src, dest, callback) {
    if (!callback) callback = new Function;
    try {
        var destDir = path.dirname(path.resolve(dest)),
            cwd = process.cwd();

        while (fs.lstatSync(src).isSymbolicLink()) {
            src = path.join(path.dirname(src), fs.readlinkSync(src));
        }

        var srcName = path.relative(destDir, src),
            destName = path.relative(destDir, dest);

        process.chdir(destDir);
        if (fs.existsSync(destName)) {
            if (fs.statSync(destName).isDirectory()) {
                fs.rmdirSync(destName);
            } else {
                fs.unlinkSync(destName);
            }
        }
        fs.symlinkSync(srcName, destName);
        process.chdir(cwd);
        callback(null);
    } catch (e) {
        callback(e);
    }
};