#! /usr/bin/env python3
"""
Create an IETF WG repository for an I-D
"""

import argparse
import os.path
import sys

import ietf_gh_utils as UTILS
import repo_utils

# Parse command line.
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--wg', '-w', required=True)
parser.add_argument('--doc', '-d', metavar='DOCNAME', required=True)
parser.add_argument('--editor', '-e', metavar='GH_ID', action='append',
                    required=True,
                    help="(can be repeated, must be at least once)")
parser.add_argument('--default-branch', '-b', action='store', default='master',
                    help="Name the primary branch in the repository")
UTILS.add_gh_auth_arguments(parser)
args = parser.parse_args(sys.argv[1:])

repo_utils.check_i_d_tools_are_installed()

WGNAME = args.wg
DOCNAME = args.doc
EDITORS = args.editor

# Fix doc name: remove draft- ietf- $WGNAME- from front
while True:
    for prefix in ('draft-', 'ietf-', WGNAME+'-'):
        found = False
        if DOCNAME.startswith(prefix):
            DOCNAME = DOCNAME[len(prefix):]
            found = True
    if not found:
        break
if len(DOCNAME) == 0:
    raise SystemExit("Docname is all prefixes!")

# Login
G, USER = UTILS.gh_login(args)

# Verify user names
if not UTILS.verify_users(G, EDITORS):
    raise SystemExit("Missing GH accounts")

# See if organization exists.
WGNAME = UTILS.fix_wg_name(WGNAME)
DOC = "draft-" + WGNAME + "-" + DOCNAME
ORG = 'ietf-wg-' + WGNAME
if not UTILS.org_exists(G, ORG):
    raise SystemExit("Organization not found; try make-ietf-wg")
o = G.get_organization(ORG)

if os.path.lexists(DOC):
    sys.exit("Error: destination path '{}' already exists.".format(DOC))

# Create an editors team and populate it
editors = o.create_team(DOC, privacy='closed')
editors.add_membership(G.get_user(USER))
done = [USER]
for e in EDITORS:
    if e not in done:
        editors.add_membership(G.get_user(e))
        done += [e]
# Add the "owners" people?

# Create repository draft-$WGNAME-$DOCNAME
repo = o.create_repo(DOC,
                     description="Repository for " + DOC + " draft",
                     has_issues=True,  # Probably the default, but this is funny
                     team_id=editors.id
                     )

# Remove pre-populated labels, add ours.
for label in repo.get_labels():
    label.delete()
repo.create_label("editorial", "41d366")
repo.create_label("design", "1d76db")
repo.create_label("parked", "f9d0c4")

initial_files = dict()
initial_files["CONTRIBUTING.md"] = repo_utils.contributing(wgname=WGNAME)
FULL_DRAFT_NAME = "draft-ietf-%(WGNAME)s-%(DOCNAME)s" % vars()
initial_files[FULL_DRAFT_NAME + ".md"] = repo_utils.initial_draft(
    full_draft_name=FULL_DRAFT_NAME, docname=DOCNAME, wg=WGNAME)

repo_utils.clone_and_create_initial_commit(
    user=ORG, repo=DOC, default_branch=args.default_branch,
    initial_files=initial_files)
repo_utils.setup_i_d_template()