# -*- encoding : utf-8 -*-

class GitGo::Connection::Base

  # @return [GitGo::Core] instance.
  attr_reader :core

  # @return [String] the current path on the host.
  attr_reader :current_path

  def initialize(core)
    @core         = core
    @current_path = ""
  end

  # Moves the instance to the provided path and remembers it for the next
  # action performed through the #bash method. It keeps the current path
  # in #current_path
  #
  # @see #bash
  # @see #current_path
  # @param [String] path the path to navigate to.
  # @return [String] the new path.
  def cd(path)
    @current_path = bash("cd '#{current_path}'; cd '#{path}'; pwd")[:stdout].chomp
  end

  # Tests to see whether the provided path is a directory.
  # It will take the path relative from #current_path if no absolute
  # path was provided.
  #
  # @param [String] path the path to test.
  # @return [true, false]
  def directory?(path)
    bash("[ -d '#{path}' ]")[:exit_code] == 0
  end

  # Tests to see whether the provided path is a file.
  # It will take the path relative from #current_path if no absolute
  # path was provided.
  #
  # @param [String] path the path to test.
  # @return [true, false]
  def file?(path)
    bash("[ -f '#{path}' ]")[:exit_code] == 0
  end

  # Creates a directory at the provided path.
  # It will take the path relative from #current_path if no absolute
  # path was provided.
  #
  # @param [String] path the path to create one or more directories for.
  # @return [Hash] containing #bash response data.
  def mkdir(path)
    bash("mkdir -p '#{path}'")
  end

  # Removes a file or directory at the provided path.
  # It will take the path relative from #current_path if no absolute
  # path was provided.
  #
  # @param [String] path the path to the file or directory to remove.
  # @return [Hash] containing #bash response data.
  def rm(path)
    bash("rm -rf '#{path}'")
  end

  # Moves a file or directory from the PATH to the NEW_PATH.
  # It will take the path relative from #current_path if no absolute
  # path was provided.
  #
  # @param [String] path the path to the file or directory to move.
  # @param [String] new_path the path to where the new file or directory should be placed.
  # @return [Hash] containing #bash response data.
  def mv(path, new_path)
    bash("mv '#{path}' '#{new_path}'")
  end

  # Closes the connection and exits the program with CODE.
  #
  # @see #close
  # @param [Integer] code the code to exit the program with.
  def close_and_exit(code = 0)
    close
    exit(code)
  end

  private

  # Sources the ~/.bashrc or ~/.zshrc files.
  # This ensures that the correct $PATH is always set and the propper binaries
  # can be accessed by the remote shell. Will only source files if present.
  #
  # @return [String] code to source the .bashrc/.zshrc files.
  def source
    [
      "if [ -f ~/.bashrc ]; then source ~/.bashrc; fi;",
      "if [ -f ~/.zshrc ]; then source ~/.zshrc; fi;",
    ].join(" ")
  end
end

