#! /usr/bin/env node
'use strict';

var findup = require("findup-sync");
var fs     = require("fs");
var shell  = require("child_process").execFile;

// Only check the value once
var baseDirectory = (function() {
    return process.env.HOME;
}());

var baseFilePath   = baseDirectory + '/.npmrc';
var baseBackupPath = baseDirectory + '/.npmrc.bak';
var nearestPath;

function isAlreadyInUse(path) {
    if (path && path !== baseFilePath) {
        return true;
    }
}

function getPath() {
    var npmrcPath = findup('.npmrc');

    if (isAlreadyInUse(npmrcPath)) {
        return npmrcPath;
    }

    return null;
}

function renameFile(currentFileName, newFileName) {
    if (fs.existsSync(currentFileName)) {
        fs.renameSync(currentFileName, newFileName);

        if (fs.existsSync(currentFileName)) {
            throw new Error("Couldn't rename file");
        }
    }
}

function copySourceToDestination(source, destination) {
    shell('/bin/cp', [source, destination]);
}

function returnToDefault() {
    renameFile(baseBackupPath, baseFilePath);
}

function backupCurrent() {
    renameFile(baseFilePath, baseBackupPath);
}

nearestPath = getPath();
if (nearestPath) {
    backupCurrent();
    copySourceToDestination(nearestPath, baseFilePath);
} else {
    returnToDefault();
}

@@ -254,20 +254,16 @@
 baseFile
-Path
    = bas
@@ -300,20 +300,16 @@
 seBackup
-Path
  = baseD
@@ -417,20 +417,16 @@
 baseFile
-Path
 ) %7B%0A    
@@ -1025,20 +1025,16 @@
 seBackup
-Path
 , baseFi
@@ -1031,28 +1031,24 @@
 up, baseFile
-Path
 );%0A%7D%0A%0Afuncti
@@ -1091,20 +1091,16 @@
 baseFile
-Path
 , baseBa
@@ -1103,20 +1103,16 @@
 seBackup
-Path
 );%0A%7D%0A%0Ane
@@ -1223,20 +1223,16 @@
 baseFile
-Path
 );%0A%7D els

remove Path from baseFile/baseBackup variable names