#!/usr/bin/env ruby -w

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

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

# Diff Tool

def check_diff_tool_cmd(git_exec)
  # Current version of git diff tool command
  ks_diff_cmd = 'ksdiff --partial-changeset --relative-path "$MERGED" -- "$LOCAL" "$REMOTE"'
  # Most minimal version of command to do loose matching
  ks_diff_loose_cmd="ksdiff"
  # Configured git diff tool
  configured_diff_tool_command = `#{git_exec} config difftool.#{KS}.cmd`
  configured_diff_tool_command.rstrip!
  # Exact match
  if configured_diff_tool_command == ks_diff_cmd
    return 1
    # Loose match
    elsif configured_diff_tool_command.include?(ks_diff_loose_cmd)
    return 2
    # No match
    else
    return 0
  end
end

# Merge Tool

def check_merge_tool_cmd(git_exec)
  # Current version of git merge tool command
  ks_merge_cmd = 'ksdiff --merge --output "$MERGED" --base "$BASE" -- "$LOCAL" --snapshot "$REMOTE" --snapshot'
  # Most minimal version of command to do loose matching
  ks_merge_loose_cmd="ksdiff"
  # Configured git merge tool
  configured_merge_tool_command = `#{git_exec} config mergetool.#{KS}.cmd`
  configured_merge_tool_command.rstrip!
  # Exact match
  if configured_merge_tool_command == ks_merge_cmd
    return 1
    # Loose match
    elsif configured_merge_tool_command.include?(ks_merge_loose_cmd)
    return 2
    # No match
    else
    return 0
  end
end

def check_merge_tool_trust_exit_code(git_exec)
  # Configured git merge tool
  configured_merge_tool_trust = `#{git_exec} config mergetool.#{KS}.trustExitCode`
  configured_merge_tool_trust.rstrip!
  # Exact match
  if configured_merge_tool_trust == 'true'
    return true
  else
    return false
  end
end

#

git_exec = git_executable_path()

diff_tool_command_result = check_diff_tool_cmd(git_exec);
merge_tool_command_result = check_merge_tool_cmd(git_exec);
merge_tool_trust = check_merge_tool_trust_exit_code(git_exec)

# Configured
if diff_tool_command_result == 1 && merge_tool_command_result == 1 && merge_tool_trust
  exit 0
end

# Needs autoupdate
if diff_tool_command_result > 0 && merge_tool_command_result > 0
  exit 202
end

exit 1
