#!/usr/bin/env python
import os
import os.path
import sys

import captainhook


def get_git_location(folder):
    if '.git' in os.listdir(folder):
        return os.path.join(folder, '.git')
    elif folder == '/':
        return False
    else:
        return get_git_location(os.path.dirname(folder))


def is_captain_hook_script(filepath):
    "Check to see if the given filepath is a captain hook owned script"
    with open(filepath, 'r') as script:
        if "CAPTAINHOOK IDENTIFIER" in script.read():
            return True
    return False


def install_pre_commit_hook():
    git_location = get_git_location(os.getcwd())
    if not git_location:
        print("You need to be in a git repo to install this.")
        sys.exit(1)
    print("Installing pre_commit.py to {0}".format(git_location))
    pre_commit_path = os.path.join(
        os.path.dirname(captainhook.__file__),
        'pre_commit.py')
    pre_commit_destination = os.path.join(
        git_location,
        'hooks',
        'pre-commit'
        )
    if os.path.exists(pre_commit_destination):
        if is_captain_hook_script(pre_commit_destination):
            print("Overriding existing captainhook script at {0}".format(
                pre_commit_destination))
        else:
            print("There is already something at {0}. "
                  "Move it and try again.".format(pre_commit_destination))
    os.system("cp {0} {1}".format(pre_commit_path, pre_commit_destination))
    os.system('chmod +x {0}'.format(pre_commit_destination))


if __name__ == '__main__':
    install_pre_commit_hook()
