#!/bin/sh
# * hook-install
#   Instala un hook en un repo
#   ssh git@host hook-install hook script repo [alt-dir]

set -e

exit 1 # I don't trust this script

hook="${1}"
script="${HOME}/.ssh/git-hooks/${2}"
repo="${3}"
clone="${4:-${repo}}"

repo="$(sed -r 's,^/*,,' <<<"$repo")"
_repo="$(sed -r -e '/(^|\/)\.\.($|\/)/d' -e "s,[^A-Za-z0-9\./_~-],,g" <<<"$repo")"
test "$repo" = "$_repo" || { printf 'Illegal name: %s\n'   "${repo}"; exit 1; }
test -d "$repo".git     || { printf 'Does not exist: %s\n' "${repo}"; exit 1; }

# Tests
test -f "${repo}.git/HEAD"
test -f "${clone}/.git/HEAD"

# Installs the generic hook that runs scripts
test -f "${repo}.git/hooks/${hook}" || ln -s "${HOME}/.ssh/git-hooks/generic" "${repo}.git/hooks/${hook}"

# Install the hook on the repo
git config -f "${repo}.git/config" --add "hacking.hooks.${hook}.${2}" "${clone}"
