#!/bin/zsh

SCRIPT_DIR=$(dirname "$0")
TOOL_PATH="$HOME/Library/Application Support/Kaleidoscope/pdb_ksdiff.py"
TOOL_SRCPATH="$SCRIPT_DIR/pdb_ksdiff.py"

if [ -r "$TOOL_SRCPATH" ] ; then
# echo "Source found $TOOL_SRCPATH"
  :
else
  echo "Could not read integration script source '$TOOL_SRCPATH'" >&2
  exit 1
fi

# Copy integration script to application support
cp "$TOOL_SRCPATH" "$TOOL_PATH" || { echo "Copy to '$TOOL_PATH' failed"; exit 1; }

# append configuration to .pdbrc
PDBRC_PATH="$HOME/.pdbrc"

if [ ! -r "$PDBRC_PATH" ] ; then
  touch "$PDBRC_PATH"
fi

## remove our integration if there
zsh "$SCRIPT_DIR/uninstall_pdb"

PDBRC_PATH=${PDBRC_PATH:A}

## integrate
cat >>"$PDBRC_PATH" <<EOL
alias ksdiff import importlib.util; __ksdiff_spec = importlib.util.spec_from_file_location("ksdiff", "$TOOL_PATH"); __ksdiff = importlib.util.module_from_spec(__ksdiff_spec); __ksdiff_spec.loader.exec_module(__ksdiff); __ksdiff.ksdiff(%*)
EOL
