#!/usr/bin/env python
# (c) 2018 Michał Górny
# Released under the terms of 2-clause BSD license.

import argparse
import errno
import os
import os.path
import sys


def main():
	argp = argparse.ArgumentParser()
	argp.add_argument('repo', help='Path to the repository')
	argp.add_argument('--overwrite', action='store_true',
			help='Overwrite existing hooks')
	vals = argp.parse_args()

	if not os.path.isdir(vals.repo):
		print('No directory found at {}'.format(vals.repo))
		return 1

	gitdir = os.path.join(vals.repo, '.git')
	if not os.path.isdir(vals.repo):
		print('No directory found at {}'.format(gitdir))
		return 1

	hooksdir = os.path.join(gitdir, 'hooks')
	try:
		os.mkdir(hooksdir)
	except OSError as e:
		if e.errno != errno.EEXIST:
			raise

	hooks_list = ('pre-rebase', 'post-merge')
	for hook in hooks_list:
		if os.path.exists(os.path.join(hooksdir, hook)):
			if vals.overwrite:
				os.unlink(os.path.join(hooksdir, hook))
			else:
				print('{} hook exists already'.format(hook))
				return 1

	for hook in hooks_list:
		with open(os.path.join(hooksdir, hook), 'w') as f:
			f.write('''#!/bin/sh
# (hook autogenerated by gv-install)

if [ "$(git symbolic-ref HEAD)" = "refs/heads/master" ]; then
	REMOTE=$(git config branch.master.remote)
	if [ -n "${REMOTE}" ]; then
		MBASE=$(git merge-base "remotes/${REMOTE}/master" master)
		if [ -n "${MBASE}" ]; then
			gverify "${MBASE}" -1
		fi
	fi
fi
''')
		os.chmod(os.path.join(hooksdir, hook), 0o755)


if __name__ == '__main__':
	sys.exit(main())
