#!/usr/bin/python

from __future__ import print_function
import argparse
import json
import os
import requests
from subprocess import check_call
import sys

def is_correct_server():
    if os.path.exists('/data/git'):
        return
    else:
        sys.exit("You can only run this on git.mysociety.org")

def parse_arguments():
    parser = argparse.ArgumentParser(description='Create a new git repository under /data/git')
    parser.add_argument('name')
    group1 = parser.add_argument_group()
    group2 = group1.add_mutually_exclusive_group(required=True)
    group2.add_argument('--public', action='store_const', const='public', dest='pubpriv', help='Public repository')
    group2.add_argument('--private', action='store_const', const='private', dest='pubpriv', help='Private repository')
    group1.add_argument('--group', help='Group name if private (defaults to privatecvs)')
    parser.add_argument('--github', action='store_true', help='Create repo on GitHub')
    args = parser.parse_args()

    if args.pubpriv == 'public':
        if args.group:
            parser.error('Do not specify a group for a public repository')
        args.group = 'publiccvs'
    else:
        if not args.group:
            args.group = 'privatecvs'

    if args.name[-4:] != '.git':
        args.name += '.git'

    return args

def git(*args):
    check_call(['git', '-C', repo_path] + list(args))


if os.geteuid() != 0:
    sys.exit("Please run as root")
is_correct_server()
ARGS = parse_arguments()
repo_path = '/data/git/{0.pubpriv}/{0.name}'.format(ARGS)

if os.path.exists(repo_path):
    sys.exit("That repository name already exists")

os.mkdir(repo_path)
git('init', '--quiet', '--bare', '--shared=group')
check_call(['chgrp', '-R', ARGS.group, repo_path])
if ARGS.pubpriv == 'private':
    check_call(['chmod', '-R', 'o-xr', repo_path])
os.symlink('/data/mysociety/bin/git-post-receive-hook', os.path.join(repo_path, 'hooks', 'post-receive'))
os.symlink('/data/mysociety/bin/git-update-hook', os.path.join(repo_path, 'hooks', 'update'))
git('config', 'receive.denynonfastforwards', 'false')
if ARGS.pubpriv == 'public':
    open(os.path.join(repo_path, 'git-daemon-export-ok'), 'a').close()

print("New repository created at /data/git/{0.pubpriv}/{0.name}".format(ARGS))

if ARGS.github:
    print("Creating on GitHub...")
    name = ARGS.name[:-4]

    j = json.load(open('/etc/mysociety/github-oauth/token.json'))
    token = j['token']
    if not token:
        sys.exit('Failed to find the GitHub API token')

    headers = {
        'Accept': 'application/vnd.github.v3+json',
        'Content-Type': 'application/json',
        'User-Agent': 'mySociety.org/1.0',
        'Authorization': 'bearer %s' % token,
    }

    data = {
        'name': name,
        'homepage': 'https://www.mysociety.org/',
        'private': ARGS.pubpriv == 'private',
    }
    url = 'https://api.github.com/orgs/mysociety/repos'
    req = requests.post(url, headers=headers, data=json.dumps(data))
    if req.status_code == 201:
        print('New repo created on GitHub')
    else:
        print('Received bad response creating repo: {0.status_code} {0.json}'.format(req))
