#!/usr/bin/env python3
"""Updates all the manifests and helm charts to use a newer ambassador version.
This must be run with an already pushed GA tag `vX.Y.Z`.
This creates a branch from vX.Y.Z, updates all the helm chart/manifest files,
commits, pushes and creates a pull request.
After that, this will create a `chart-A.B.C` tag, where A.B.C is the version
in charts/ambassador/Chart.yaml
"""

from os import getenv
import datetime
import fileinput
import os.path
import re
import sys
import argparse
from contextlib import contextmanager
from typing import Generator
from shutil import which

from lib import base_version, build_version, git_add, git_check_clean, re_ga, vX, vY, ansiterm, get_gh_repo
from lib.uiutil import Checker, CheckResult, run
from lib.uiutil import run_txtcapture as run_capture
from lib.gitutil import has_open_pr


def main(next_ver: str, today: datetime.date, quiet: bool=False, commit: bool = True, promote_path: str = '', aes_ver: str = '') -> int:
    if which("gh") is None:
        print("gh tool is not installed.")
        print("Please install the tool and rerun this script:")
        print("https://github.com/cli/cli#installation")
        return 1
    checker = Checker()

    @contextmanager
    def check(name: str) -> Generator[CheckResult, None, None]:
        with checker.check(name) as subcheck:
            # time.sleep(1)  # it's stupid, but honestly the delay makes the output more readable
            yield subcheck

    warning = """
 ==> Warning: FIXME: This script does not have the property that if
     something goes wrong, you can just restart it; put another way:
     it does not have the property that each step is idempotent.
     If something does go wrong, then you'll have to address it, then
     resume where the script left off by going through the checklist
     manually (or by commenting out the already-completed steps).
"""
    print(f"{ansiterm.sgr.fg_red}{warning}{ansiterm.sgr}")

    if not getenv("GITHUB_TOKEN"):
        run(["gh", "auth", "login"])

    user = getenv("USER")
    if user is None or user == '':
        user = 'unknownuser'
    workbranch = f"{user}/v{next_ver}/chart-image-updates"
    image_tag = next_ver
    if promote_path != '':
        image_tag = f"{image_tag}-{promote_path}"

    with check(f"Creating new branch {workbranch} off of tag v{next_ver}"):
        cur_branch = run_capture(['git', 'rev-parse', '--abbrev-ref', 'HEAD'])

        if cur_branch != workbranch:
            run(["git", "fetch", "--tags"])
            run(["git", "checkout", f"v{next_ver}", "-b", workbranch])

    if not checker.ok:
        return 1

    print('TODO: CHECK THAT IMAGE EXISTS')
    if aes_ver != '':
        with check(f"Updating AES image tag to {aes_ver}"):
            run(["make", f"AES_IMAGE_TAG={aes_ver}", "release/chart/aes-image-update"])
        if not checker.ok:
            return 1

    with check(f"Updating image tag in charts"):
        run(["make", f"IMAGE_TAG={image_tag}", "release/chart/update-images"])
        git_add("charts/ambassador/Chart.yaml")
        git_add("charts/ambassador/CHANGELOG.md")
        git_add("charts/ambassador/README.md")
        git_add("charts/ambassador/values.yaml")

    if not checker.ok:
        return 1

    with check(f"Updating manifest yaml"):
        run(["make", "BUMP_STABLE=true", "update-yaml"])
        git_add("manifests")
        git_add("docs/yaml")

    with check('Update charts/ambassador/README.md'):
        for line in fileinput.FileInput("charts/ambassador/README.md", inplace=True):
            line_regex = '^\|\s*`image.tag`\s+\|.*\|\s+`\d+\.\d+\.\d+`\s*\|$'
            if re.match(line_regex, line):
                replace = "`{}`".format(next_ver)
                line = re.sub("`\d+\.\d+\.\d+`", replace, line)
            sys.stdout.write(line)
        git_add("charts/ambassador/README.md")

    if checker.ok and commit:
        with check(f"Committing changes..."):
            gitdir = run_capture(['git', 'rev-parse', '--git-dir'])
            with open(os.path.join(gitdir, 'GITGUI_MSG'), 'w') as msgfile:
                msgfile.write(f"Updating and manifest images for v{next_ver}\n")
            if getenv("AMBASSADOR_RELENG_NO_GUI"):
                run(['git', 'commit', '-am', f'Update for v{next_ver}'])
            else:
                run(['git', 'citool'])
            run(["git", "push", "-u", "origin", workbranch])
        if not checker.ok:
            return 1
        with check(f"Creating pull request for chart and manifest changes"):
            m = re_ga.match(next_ver)
            assert m
            long_lived_release_branch = f"release/v{m[vX]}.{m[vY]}"
            curr_release_branch = f"rel/v{next_ver}"
            target_branch = long_lived_release_branch
            if has_open_pr(get_gh_repo(), long_lived_release_branch, curr_release_branch):
                target_branch = curr_release_branch
            # TODO: dont hardcode owners
            run(["gh", "pr", "create",
                    "--repo", get_gh_repo(),
                    "--base", target_branch,
                    "--title", f"[v{next_ver}] Chart and manifest image updates",
                    "--body", f"Update charts and manifests to use the newly release images for {next_ver}",
                    "--reviewer", "kflynn,rhs,esmet,acookin"])
    if checker.ok:
        if getenv("AMBASSADOR_RELENG_NO_GUI"):
            run(["gh", "pr", "view", workbranch, "--repo", get_gh_repo()])
        else:
            run(["gh", "pr", "view", workbranch, "--repo", get_gh_repo(), "--web"])
        return 0
    else:
        return 1


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Edit image values for ambassador helm charts.')
    parser.add_argument('--quiet', dest='quiet', default=False, action='store_true')
    parser.add_argument('--no-commit', dest='no_commit', default=False, action='store_true')
    parser.add_argument('--promote-path', default="")
    parser.add_argument('--oss-version', required=True)
    parser.add_argument('--aes-version', default="")
    args = parser.parse_args()

    quiet = False
    commit = True

    if args.quiet:
        quiet = True
    if args.no_commit:
        commit = False

    if not re_ga.match(args.oss_version):
        sys.stderr.write("--oss-version must be X.Y.Z")
        sys.exit(2)
    if args.aes_version != "" and not re_ga.match(args.aes_version):
        sys.stderr.write("--aes-version must be X.Y.Z")
        sys.exit(2)

    sys.exit(main(
        next_ver=args.oss_version,
        today=datetime.date.today(),
        quiet=quiet,
        commit=commit,
        promote_path=args.promote_path,
        aes_ver=args.aes_version,
    ))
