'use strict';

var execFile = require('child_process').execFile;
var util     = require('util');
var p        = require('path');

function SambaClient(options) {
  this.address  = options.address;
  this.username = options.username || 'guest';
  this.password = options.password;
}

SambaClient.prototype.getFile = function(path, destination, cb) {
  this.runCommand('get', path, destination, cb);
};

SambaClient.prototype.sendFile = function(path, destination, cb) {
  this.runCommand('put', path, destination.replace('/', '\\'), cb);
};

SambaClient.prototype.runCommand = function(cmd, path, destination, cb) {
  var workingDir   = p.dirname(path);
  var fileName     = p.basename(path).replace('/', '\\');
  var fullCmd      = util.format('%s %s %s', cmd, fileName, destination);

SambaClient.prototype.getSmbClientArgs = function(fullCmd) {
  var args = ['-U', this.username];

  if (!this.password) {
    args.push('-N');
  }

  args.push('-c', fullCmd, this.address);

  if (this.password) {
    args.push(this.password);
  }

  return args;
};

SambaClient.prototype.execute = function(cmd, cmdArgs, workingDir, cb) {
  var fullCmd = util.format('%s %s', cmd, cmdArgs);

  var args = this.getSmbClientArgs(fullCmd);

  var options = {
    cwd : workingDir
  };

  execFile('smbclient', args, options, function(err, stdout, stderr) {
    var allOutput = (stdout + stderr);
    cb(err, allOutput);
  });
};

SambaClient.prototype.runCommand = function(cmd, path, destination, cb) {
  var workingDir   = p.dirname(path);
  var fileName     = p.basename(path).replace('/', '\\');
  var cmdArgs      = util.format('%s %s', fileName, destination);

  this.execute(cmd, cmdArgs, workingDir, cb);
};

module.exports = SambaClient;

@@ -552,34 +552,29 @@
 t.prototype.
-runCommand
+mkdir
  = function(
@@ -577,113 +577,188 @@
 ion(
-cmd, path, destination, cb) %7B%0A  var workingDir   = p.dirname(path);%0A  var fileName     = p.basename(p
+remotePath, cb) %7B%0A  this.execute('mkdir', remotePath.replace('/', '%5C%5C'), __dirname, cb);%0A%7D;%0A%0ASambaClient.prototype.dir = function(remotePath, cb) %7B%0A  this.execute('dir', remoteP
 ath
-)
 .rep
@@ -776,82 +776,313 @@
 %5C%5C')
-;%0A  var fullCmd      = util.format('%25s %25s %25s', cmd, fileName, destination)
+, __dirname, cb);%0A%7D;%0A%0ASambaClient.prototype.fileExists = function(remotePath, cb) %7B%0A  this.dir(remotePath, function(err, allOutput) %7B%0A%0A    if (err && allOutput.match(/NT_STATUS_NO_SUCH_FILE/im)) %7B%0A      return cb(null, false);%0A    %7D else if (err) %7B%0A      return cb(err);%0A    %7D%0A%0A    cb(null, true);%0A  %7D);%0A%7D
 ;%0A%0AS

add mkdir, dir, fileExists