#!/usr/bin/env bash

[[ $# -ge 1 ]] && [[ -f "$1" ]] && input="$1" || input="-"

get_script_dir () {
  src="${BASH_SOURCE[0]}"

  while [[ -h "$src" ]]; do
    dir="$(cd -P "$( dirname "$src" )" && pwd)"
    src="$(readlink "$src")"
    [[ $src != /* ]] && src="$dir/$src"
  done

  dir="$(cd -P "$( dirname "$src" )" && pwd)"
  echo "$dir"
}

# find my sed
hash gsed 2> /dev/null && SED=gsed || SED=sed

# find my diff-highlight
if hash diff-highlight 2> /dev/null; then
  diff_highlight=diff-highlight
else
  diff_highlight="/usr/share/git/diff-highlight/diff-highlight"
fi

CSI=$'\x1b\['
NL="
"
color_code_regex="(${CSI}([0-9]{1,3}(;[0-9]{1,3}){0,3})[m|K])?"

git_index_line_pattern="^($color_code_regex)index .*"

format_diff_header () {
  # simplify the unified patch diff header
    $SED -E "/$git_index_line_pattern/{N;s/$git_index_line_pattern\n//;}" \
    | $SED -E "s/^($color_code_regex)\-\-\-(.*)$/\1$(print_horizontal_rule)\\${NL}\1\-\-\-\-\5/g" \
    | $SED -E "s/^($color_code_regex)\+\+\+(.*)$/\1\+\+\+\+\5\\${NL}\1$(print_horizontal_rule)/g"
}

print_horizontal_rule () {
  let width="$(tput cols)"

  if [[ $(uname -s) =~ (MINGW32*|MSYS*) ]]; then
    width=$(( width - 1 ))
  fi

  # echo -n '─' | hexdump -C
  local -r dash=$( printf "%b" "\xe2\x94\x80" )
  printf "%*s\n" "$width" | $SED "s/ /${dash}/g"
}

print_header_clean () {
  "/usr/share/diff-so-fancy/diff-so-fancy.pl"
}

# run it.
# shellcheck disable=SC2002
cat $input \
  | $diff_highlight \
  | format_diff_header \
  | print_header_clean
