"""
Higher level commands for github pipeline
"""

from __future__ import absolute_import, unicode_literals

import argparse
import io
import logging
import os
import pipes
import random
import shutil
import subprocess
import sys
import tempfile

if True:
  if os.path.samefile(sys.path[0], os.path.dirname(__file__)):
    sys.path.pop(0)

  import github
  import keyring
  from packaging import version as versiontool
  import magic

logger = logging.getLogger(__name__)

PSEUDO_MESSAGE = """
This is a pseudo-release used only to stage artifacts for the release pipeline.
Please do not rely on the artifacts contained in this release as they change
frequently and are very likely to be broken.
""".replace("\n", " ")


def get_access_token():
  if "GITHUB_ACCESS_TOKEN" in os.environ:
    return os.environ["GITHUB_ACCESS_TOKEN"]

  credential = keyring.get_credential("api.github.com", None)
  if credential is not None:
    return credential.password

  raise RuntimeError(
      "No github access token found, please set GITHUB_ACCESS_TOKEN "
      "environment variable or add username@api.github.com to your "
      "system keyring, e.g. run `keyring set api.github.com <username>`")


def create_pseudorelease_tag(reposlug, branch):
  # TODO(josh): get title out of the script so that it can be reusable
  hub = github.Github(get_access_token())
  repo = hub.get_repo(reposlug)
  branchobj = repo.get_branch(branch)
  logger.info("Creating tag pseudo-%s -> %s", branch, branchobj.commit.sha)
  refname = "tags/pseudo-" + branch
  try:
    existing_ref = repo.get_git_ref(refname)
    logger.info("Updating existing ref for %s", refname)
    existing_ref.edit(branchobj.commit.sha, force=True)
    return
  except github.UnknownObjectException:
    pass

  logger.info("Creating ref %s", refname)
  refname = "refs/" + refname
  repo.create_git_ref(refname, branchobj.commit.sha)


INITDIRS = [
    "branches",
    "hooks",
    "info",
    "objects/info",
    "objects/pack",
    "refs/heads",
    "refs/tags",
]

CONFIGTPL = """
[core]
	repositoryformatversion = 0
	filemode = true
	bare = true
[remote "origin"]
	url = {}
  fetch = +refs/heads/*:refs/heads/*
"""

MSGTPL = """Sync {commit_name}

This commit was automatically generated by the upstream build.

Upstream-Commit: {upstream_commit}
"""

CHARS = "abcdefghijklmnopqrstuvwxzyABCDEFGHIJKLMNOPQRSTUVWXYZ012345679"


def make_randstr(strlen=10):
  """Generate a random string."""
  return ''.join(random.choice(CHARS) for i in range(strlen))


def init_repository(repodir, repo_url):
  """
  Ensure that the specified directory is configured as a git repository.
  We create any missing directories and overwrite the config and HEAD files,
  putting the repository directory into a known state without blowing away
  the object cache.
  """

  # Ensure that the standard directories exit
  for dirname in INITDIRS:
    dirpath = os.path.join(repodir, dirname)
    if os.path.lexists(dirpath):
      if os.path.islink(dirpath) or not os.path.isdir(dirpath):
        os.unlink(dirpath)
      else:
        continue
    os.makedirs(dirpath)

  # Write out the config and the HEAD files
  outpath = os.path.join(repodir, "config")
  with io.open(outpath, "w", encoding="utf-8") as outfile:
    outfile.write(CONFIGTPL.format(repo_url))
  outpath = os.path.join(repodir, "HEAD")
  with io.open(outpath, "w", encoding="utf-8") as outfile:
    outfile.write("ref: refs/heads/master")


def canonicalize_trailer_key(keystr):
  """Return canonical capitalization for a trailer key"""
  return "-".join(part.capitalize() for part in keystr.split("-"))


def get_trailers(repodir, commit):
  """Return a dictionary of git commit trailers."""
  proc = subprocess.Popen([
      "git", "show", "--no-patch", '--format="%(trailers:unfold)',
      commit], cwd=repodir, stdout=subprocess.PIPE)

  out = {}
  with proc.stdout as stdout:
    for line in stdout:
      line = line.strip().decode("utf-8")
      if ":" not in line:
        continue
      key, value = line.split(":", 1)
      if ", " in value:
        value = value.split(", ")
      out[canonicalize_trailer_key(key)] = value
  proc.wait()
  if proc.returncode != 0:
    cmdstr = " ".join(pipes.quote(arg) for arg in proc.args)
    raise subprocess.CalledProcessError(proc.returncode, cmdstr)
  return out


def ref_exists(repodir, refname):
  return subprocess.call(
      ["git", "show-ref", "--verify", "--quiet", "refs/" + refname],
      cwd=repodir) == 0


def sync_doc_artifacts(
    docrepo_url, docrepo_dir, scratch_dir, stage_dir, deploy_key_path,
    branch=None, tag=None):

  current_commit = subprocess.check_output(
      ["git", "rev-parse", "HEAD"]).strip().decode("utf-8")

  env = os.environ.copy()
  if deploy_key_path:
    env["GIT_SSH_COMMAND"] = "ssh -i {} -F /dev/null".format(deploy_key_path)

  # Initialize and fetch the docrepo clone
  init_repository(docrepo_dir, docrepo_url)
  subprocess.check_call([
      "git", "fetch", "--prune", "--tags"], cwd=docrepo_dir, env=env)

  # Create a temporary branchname for us to do our work in
  workbranch = "work-" + make_randstr(10)

  # Clear out scratch tree
  if os.path.exists(scratch_dir):
    shutil.rmtree(scratch_dir)
  os.makedirs(scratch_dir)

  if branch:
    commit_name = branch
    if ref_exists(docrepo_dir, "heads/" + branch):
      # If the branch already exists on the remote, then check it out at
      # it's current state
      subprocess.check_call(
          ["git", "--git-dir=" + docrepo_dir, "--work-tree=" + scratch_dir,
           "checkout", "-b", workbranch, branch])
    else:
      # Otherwise create a new orphan branch for it
      subprocess.check_call(
          ["git", "--git-dir=" + docrepo_dir, "--work-tree=" + scratch_dir,
           "checkout", "--orphan", workbranch])
  elif tag:
    commit_name = tag
    if ref_exists(docrepo_dir, "tags/" + tag):
      # If the tag already exists on the remote then checkout it's parent
      subprocess.check_call(
          ["git", "--git-dir=" + docrepo_dir, "--work-tree=" + scratch_dir,
           "checkout", "-b", workbranch, "{}^".format(tag)])
    else:
      # Otherwise checkout the current HEAD of master and just use that.
      subprocess.check_call(
          ["git", "--git-dir=" + docrepo_dir, "--work-tree=" + scratch_dir,
           "checkout", "-b", workbranch, "master"])
  else:
    raise ValueError("Both branch and tag are empty")

  subprocess.check_call(
      ["git", "--git-dir=" + docrepo_dir, "--work-tree=" + stage_dir,
       "add", "-A"])

  result = subprocess.call(
      ["git", "diff", "--quiet", "--exit-code", "--cached"],
      cwd=docrepo_dir)
  if result == 0:
    # There is nothing to commit, the doc sources have not changed.
    return

  tfile = tempfile.NamedTemporaryFile(
      delete=False, prefix="gitmsg-", mode="w")
  with tfile as outfile:
    msgpath = outfile.name
    outfile.write(MSGTPL.format(
        commit_name=commit_name, upstream_commit=current_commit))
  subprocess.check_call([
      "git", "--git-dir=" + docrepo_dir, "--work-tree=" + stage_dir,
      "commit", "--file", msgpath])
  os.unlink(msgpath)

  if branch:
    subprocess.check_call(
        ["git", "push", "-f", "origin", "{}:{}".format(workbranch, branch)],
        cwd=docrepo_dir, env=env)
  elif tag:
    subprocess.check_call(
        ["git", "tag", "-f", tag],
        cwd=docrepo_dir)
    subprocess.check_call(
        ["git", "push", "-f", "origin", "{0}:{0}".format(tag)],
        cwd=docrepo_dir, env=env)


PSEUDO_MESSAGE = """\
This is a pseudo-release used only to stage artifacts for the release pipeline.
Please do not rely on the artifacts contained in this release as they change
frequently and are very likely to be broken.
""".replace("\n", " ")


def push_release(reposlug, tag, message_path, filepaths):
  message = ""
  if message_path:
    with io.open(message_path, encoding="utf-8") as infile:
      message = infile.read()

  # TODO(josh): get title out of the script so that it can be reusable
  prerelease = False
  title = reposlug.split("/", 1)[1].replace("_", "-") + " " + tag

  if tag.startswith("pseudo-"):
    prerelease = True
    title = "pseudo-release artifacts for " + tag[len("pseudo-"):]
  else:
    try:
      version = versiontool.parse(tag)
      if version.is_devrelease or version.is_prerelease:
        prerelease = True
    except versiontool.InvalidVersion:
      version = None

  filenames = set(filepath.rsplit(os.sep, 1)[-1] for filepath in filepaths)
  hub = github.Github(get_access_token())
  repo = hub.get_repo(reposlug)

  try:
    release = repo.get_release(tag)
    logger.info("Found release for tag %s", tag)
  except github.UnknownObjectException:
    logger.info("Creating release for tag %s", tag)
    try:
      release = repo.create_git_release(
          tag, title, message, prerelease=prerelease)
    except github.UnknownObjectException:
      logger.warning("Can't create a release for tag %s", tag)
      raise

  if release.title != title or release.body != message:
    logger.info("Updating release message for: %d", release.id)
    release.update_release(title, message, prerelease=prerelease)

  for asset in release.get_assets():
    if asset.name in filenames:
      logger.info("Deleting asset %s", asset.name)
      asset.delete_asset()

  for filepath in filepaths:
    filename = filepath.rsplit(os.sep, 1)[-1]
    mime = magic.Magic(mime=True)
    release.upload_asset(
        filepath, content_type=mime.from_file(filepath), name=filename)


def setup_argparser(argparser):
  argparser.add_argument(
      "-l", "--log-level", default="info",
      choices=["debug", "info", "warning", "error"])
  subparsers = argparser.add_subparsers(dest="command")

  subparser = subparsers.add_parser(
      "create-pseudorelease-tag", help=(
          "Create a tag pseudo-<branch> pointing to the current head of "
          "<branch> on github."
      ))
  subparser.add_argument("reposlug")
  subparser.add_argument("branch")

  subparser = subparsers.add_parser(
      "sync-doc-artifacts", help=(
          "Given the currently checked-out commit within an export repository,"
          " create a new commit in the corresponding documentation artifacts"
          " repository."
      ))
  subparser.add_argument(
      "--doc-repo", dest="docrepo_url",
      help="URL of the documentation repository")
  subparser.add_argument(
      "--repo-dir", dest="docrepo_dir",
      help="path to where we should checkout the doc artifacts repo")
  subparser.add_argument(
      "--scratch-tree", dest="scratch_dir",
      help="directory to use as git work-tree for intermediate steps")
  subparser.add_argument(
      "--stage", dest="stage_dir",
      help="directory that contains the new content for the repository")
  subparser.add_argument(
      "--deploy-key", dest="deploy_key_path", nargs="?",
      help="Path to the deploy key for the documentation repository")

  mgroup = subparser.add_mutually_exclusive_group(required=True)
  mgroup.add_argument(
      "--branch",
      help="Name of the target branch to push to")
  mgroup.add_argument(
      "--tag",
      help="Name of the target tag to push to")

  subparser = subparsers.add_parser(
      "push-release", help=(
          "Create or modify the release for the currently built tag on travis."
      ))

  subparser.add_argument(
      "-m", "--message",
      help="path to a file containing release notes message")
  subparser.add_argument("--repo-slug", required=True)
  subparser.add_argument("--tag", help="the tag we are deploying")
  subparser.add_argument("files", nargs="*", help="files to upload")


def get_argdict(namespace):
  blacklist = tuple()
  out = {}
  for key, value in vars(namespace).items():
    if key.startswith("_"):
      continue
    if key in blacklist:
      continue
    out[key] = value
  return out


def main():
  logging.basicConfig(level=logging.INFO)
  argparser = argparse.ArgumentParser(description=__doc__)
  setup_argparser(argparser)

  try:
    import argcomplete
    argcomplete.autocomplete(argparser)
  except ImportError:
    pass

  args = argparser.parse_args()
  logging.getLogger().setLevel(getattr(logging, args.log_level.upper()))

  if hasattr(args, "tag"):
    tagstr = getattr(args, "tag")
    travis_tag = os.environ.get("TRAVIS_TAG", tagstr)

    if travis_tag != tagstr:
      # If this is a travis incremental build, then stage artifacts under the
      # pseudo-release instead of creating a new release for the tag.
      if travis_tag.startswith("pseudo-"):
        setattr(args, "tag", travis_tag)
      else:
        logger.error(
            "Cowardly refusing to to create a github release '%s' from a travis"
            "build of tag '%s'", tagstr, os.environ["TRAVIS_TAG"])
        sys.exit(1)

  argdict = get_argdict(args)
  command = argdict.pop("command")
  argdict.pop("log_level")

  if command == "create-pseudorelease-tag":
    create_pseudorelease_tag(args.reposlug, args.branch)
  elif command == "sync-doc-artifacts":
    tag = argdict.pop("tag")
    if tag.startswith("pseudo-"):
      argdict["branch"] = tag[len("pseudo-"):]
    else:
      argdict["tag"] = tag
    sync_doc_artifacts(**argdict)
  elif command == "push-release":
    push_release(args.repo_slug, args.tag, args.message, args.files)
  else:
    logger.error("Unknown command %s", command)
    sys.exit(1)


if __name__ == "__main__":
  main()
