#!/usr/bin/env ruby -w

require File.join(File.dirname(File.expand_path(__FILE__)), 'git_support')

# Tool name
KS = 'Kaleidoscope'
PromptFalse = 'false'

def configure_diff_tool_cmd(git_exec)
  command = 'ksdiff --partial-changeset --relative-path \"\$MERGED\" -- \"\$LOCAL\" \"\$REMOTE\"'
  `#{git_exec} config --global difftool.#{KS}.cmd "#{command}"`
  if $?.exitstatus == 0
    return true
  end
  $stderr.puts "Could not create a #{KS} diff tool"
  exit 2
end

def configure_diff_tool_prompt(git_exec)
  `#{git_exec} config --global difftool.prompt false`
  if $?.exitstatus == 0
    return true
  end
  $stderr.puts "Could not disable the prompt for 'git difftool'"
  exit 3
end

def configure_diff_tool(git_exec)
  `#{git_exec} config --global diff.tool #{KS}`
  if $?.exitstatus == 0
      return true
  end
  $stderr.puts "Could not set #{KS} as the default diff tool'"
  exit 4
end

def configure_merge_tool_cmd(git_exec)
  command = 'ksdiff --merge --output \"\$MERGED\" --base \"\$BASE\" -- \"\$LOCAL\" --snapshot \"\$REMOTE\" --snapshot'
  `#{git_exec} config --global mergetool.#{KS}.cmd "#{command}"`
  if $?.exitstatus == 0
    return true
  end
  $stderr.puts "Could not create a #{KS} merge tool"
  exit 5
end

def configure_merge_tool_prompt(git_exec)
    `#{git_exec} config --global mergetool.prompt false`
    if $?.exitstatus == 0
        return true
    end
    $stderr.puts "Could not disable the prompt for 'git mergetool'"
    exit 6
end

def configure_merge_tool_trust_exit_code(git_exec)
	`#{git_exec} config --global mergetool.#{KS}.trustExitCode true`
	if $?.exitstatus == 0
		return true
	end
	$stderr.puts "Could not configure git to trust ksdiff's exit code"
	exit 7
end

def configure_merge_tool(git_exec)
    `#{git_exec} config --global merge.tool #{KS}`
    if $?.exitstatus == 0
        return true
    end
    $stderr.puts "Could not set #{KS} as the default merge tool'"
    exit 8
end

git_exec = git_executable_path()

configure_diff_tool_cmd(git_exec)
configure_diff_tool(git_exec)
configure_diff_tool_prompt(git_exec)
configure_merge_tool_cmd(git_exec)
configure_merge_tool_prompt(git_exec)
configure_merge_tool_trust_exit_code(git_exec)
configure_merge_tool(git_exec)
