#!/usr/bin/python3
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'python'))

import re
import subprocess
from typing import TextIO

from sl_run_git_command import run_git_command
from termcolor import colored

sys.path.insert(0, str(Path.cwd() / 'scripts' / 'python'))
from kutil import config

branch = (sys.argv[1:] or ['origin/master'])[0]
to_checkout = ['config', 'blacklist.conf']
to_rm = {}

print(colored(f"Merging {branch}", 'green'));
try:
    output = run_git_command('merge', branch, exit_on_error=False).stdout
except subprocess.CalledProcessError as e:
    output = e.stdout
    print(colored("Merge failed, attempting to resolve conflicts...", 'yellow'))

for line in output.splitlines():
    if line.startswith("CONFLICT") and " patches.kernel.org/" in line:
        continue
    if line.startswith("Auto-merging "):
        continue
    if line.startswith("CONFLICT (content): Merge conflict in config/"):
        continue
    if line.startswith("CONFLICT (content): ") and " patches." in line:
        patch_file = line.split()[-1]
        to_checkout.append(patch_file)
        continue
    if line.startswith("CONFLICT (modify/delete): ") and "deleted in" in line and "modified in HEAD." in line:
        patch_file = line.split()[2]
        to_rm[patch_file] = True
        continue

    print(line)

run_git_command('checkout', branch, '--', *to_checkout, capture_output=False)

deleted = run_git_command('rm', 'patches.kernel.org/[0-9]*.patch').stdout.splitlines()
print(colored(f"\nDeleted {len(deleted)} patches.kernel.org/", 'green'))

src_version = config.read_config_sh('rpm').get('srcversion')
try:
    for patch_file in run_git_command('grep', '-l', f"Patch-mainline: v*{re.escape(src_version)}", '--', 'patches.*',
                                      exit_on_error=False).stdout.splitlines():
        to_rm[patch_file] = True
except subprocess.CalledProcessError:
	print("nothing from mainline to delete...")

to_rm_pattern = {}
if to_rm:
    print(colored("\nDeleting other:", 'green'))
    run_git_command('rm', *to_rm.keys(), capture_output=False)
    for patch_file in to_rm:
        to_rm_pattern[f"\t{patch_file}\n"] = True

print(colored("\nUpdating series.conf", 'green'))

def consume_comments(f: TextIO) -> list[str]:
    ret = []
    for ln in f:
        ret += ln
        if not ln.startswith("\t#"):
            break
    return ret

def consume_kernel_org(f: TextIO) -> list[str]:
    ret = consume_comments(f)

    prev_line = None
    for ln in f:
        if ln.startswith("\t# Build fixes"):
            if prev_line:
                ret += prev_line
            ret += ln
            return ret
        prev_line = ln

    raise RuntimeError("Failed to find end of kernel.org patches section")

def consume_sorted(f: TextIO) -> list[str]:
    ret = consume_comments(f)

    for ln in f:
        # Either
        # # tip/tip or alike
        # or
        # #############...
        if ln.startswith("\t#"):
            ret += ln
            return ret

    raise RuntimeError("Failed to find end of sorted patches section")

lines = []
with open('series.conf', encoding='utf-8') as f:
    for ln in f:
        if ln.startswith("\t# latest standard kernel patches"):
            lines += ln
            lines += consume_kernel_org(f)
            continue
        if ln.startswith("\t# sorted patches"):
            lines += ln
            lines += consume_sorted(f)
            continue
        if not ln in to_rm_pattern:
            lines += ln

with open('series.conf', 'w', encoding='utf-8') as f:
    f.writelines(lines)

print(colored("\nDone, git diff:", 'green'))
run_git_command('--no-pager', 'diff', capture_output=False)
