#!/usr/bin/env bash
#
# Copyright 2015 Tickle Labs, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# Paths
git_path=".git"
git_hook_path="${git_path}/hooks"
backup_git_hook_path="${git_hook_path}.original"
script_home=".githooks"
entry_script_path="${script_home}/entry.py"
entry_container_path="${script_home}/entry"
git_hook_link_target="../${entry_container_path}"

# Check git
if !(git status 1>/dev/null 2>&1 && [ -d "${git_path}" ]); then
    echo -e "\033[33mCannot find \`.git\` folder (at current directory) to setup git hooks.\033[m"
    exit 1
fi

# Check Python dependency
python -c "import submarine-githooks" 1>/dev/null 2>&1 || pip install -U submarine-githooks

# Check if installed
if [ "`SUBMARINE_GITHOOK_INSTALL_TEST=1 ${entry_script_path}`" != "submarine-githooks 1" ]; then
    echo -e "\033[31mCannot find \"${entry_script_path}\"\033[m"
    echo -e "\033[31mCall \`submarine-githooks install\` to setup githooks instead of running this\033[m"
    exit 2
fi

# Setup links
if [ "`readlink .git/hooks`" != "${git_hook_link_target}" ]; then
    mv ${git_hook_path} ${backup_git_hook_path} && ln -s ${git_hook_link_target} ${git_hook_path}
fi
