#!/bin/sh
set -e

if [ -n "$1" ]; then
  CANVAS_ROOT=$1
fi

if [ -z "$2" ]; then
  $0 "$CANVAS_ROOT" $CANVAS_ROOT".git" "."
  if [ -d "$CANVAS_ROOT"gems/plugins ]; then
    for plugin in $(find $CANVAS_ROOT"gems/plugins" -name .git | sort); do
      $0 "$CANVAS_ROOT" $plugin "../../.."
    done
  fi
  exit 0
fi

GIT_DIR=$2
HOOKS_PREFIX=$3

if [ ! -d "$GIT_DIR" ]; then
  exit 0
fi

echo running for git dir $GIT_DIR

GLOB_PATTERN=$CANVAS_ROOT"hooks/*"

for hook in $GLOB_PATTERN; do
  hook_name=${hook##*/}
  git_path="$GIT_DIR/hooks/$hook_name"
  # make sure file exists
  touch "$git_path"
  # make sure it has a shebang prepending if necessary
  grep -qF -- "#!" "$git_path" || (echo "#!/bin/sh" | cat - $git_path > "$git_path-temp" && mv "$git_path-temp" $git_path)
  # make sure it is executable
  [ -x "$git_path" ] || chmod +x "$git_path"
  # # put in line to call this hook
  grep -qF -- "$HOOKS_PREFIX/hooks/$hook_name" "$git_path" || echo "$HOOKS_PREFIX/hooks/$hook_name" >> "$git_path"
done

exit 0
