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

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

import argparse
import atexit
import subprocess

from pygit2 import (
    CredentialType,
    Keypair,
    Oid,
    RemoteCallbacks,
    Repository,
    enums,
)
from pygit2.callbacks import _Credentials
from pygit2.remotes import TransferProgress
from slaby_scripts.git import run_git_command

argparser = argparse.ArgumentParser(description='Rebase work onto devel and push to origin')
argparser.add_argument('--continue', action='store_true', help='Continue rebase if in progress')
args = argparser.parse_args()
cont = vars(args)['continue']

repo = Repository('.')
child = None

cur_branch = None if repo.head_is_detached else repo.head.shorthand
if not cont and cur_branch == 'work':
    run_git_command('rebase', 'work', 'devel', capture_output=False)
elif cur_branch != 'devel':
    raise RuntimeError(f"not on {'work or ' if not cont else ''}devel branch: on {cur_branch if cur_branch else '<nothing>'}")

class MyRemoteCallbacks(RemoteCallbacks):
    def __init__(self) -> None:
        super().__init__()
        self.push_failed = False
        self.cred_tried = False

    def limit_transfer_progress(self, stats: TransferProgress) -> tuple[bool, bool]:
        # final (or nothing to do) print
        if stats.received_objects == stats.total_objects and stats.indexed_objects == stats.total_objects:
            return (True, True)

        # initial print
        if stats.received_objects == 0:
            return (True, False)

        # receiving objects
        if stats.received_objects != stats.total_objects:
            return (stats.received_objects % 100 == 0, False)

        # indexing objects
        return (stats.indexed_objects % 100 == 0, False)

    def transfer_progress(self, stats: TransferProgress) -> None:
        (limit, final) = self.limit_transfer_progress(stats)
        if limit:
            print(f"Received {stats.received_objects}/{stats.total_objects} objects ({stats.indexed_objects} indexed)",
                  end='\n' if final else '\r', flush=True)

    def update_tips(self, refname: str, old: Oid, new: Oid) -> None:
        print(f"Updated {refname} from {str(old)[:12]} to {str(new)[:12]}")

    def credentials(self, url: str, username_from_url: str | None, allowed_types: CredentialType) -> _Credentials:
        if self.cred_tried:
            raise RuntimeError(f"Authentication failed for {url} (username: {username_from_url})")
        self.cred_tried = True

        if allowed_types & enums.CredentialType.SSH_KEY:
            priv = Path.home() / '.ssh' / 'korg-jirislaby'
            pub = priv.with_suffix('.pub')
            return Keypair(username_from_url, pub, priv, None)

        raise RuntimeError(f"No suitable credentials for {url} (username: {username_from_url}, allowed types: {allowed_types:x})")

    def limit_push_transfer_progress(self, current: int, total: int) -> tuple[bool, bool]:
        # final (or nothing to do) print
        if current == total:
            return (True, True)

        # initial print
        if current == 0:
            return (True, False)

        return (current % 10 == 0, False)

    def push_transfer_progress(self, current: int, total: int, nbytes: int) -> None:
        (limit, final) = self.limit_push_transfer_progress(current, total)
        if limit:
            print(f"Pushed {current}/{total} objects ({nbytes} bytes)",
                  end='\n' if final else '\r', flush=True)

    def push_update_reference(self, refname: str, status: str) -> None:
        if status:
            print(f"Failed to update {refname}: {status}")
            self.push_failed = True
        else:
            print(f"Updated {refname}")

if not cont:
    child = subprocess.Popen(['ssh', 'git@gitolite.kernel.org', 'track', 'fetch',
                              'pub/scm/linux/kernel/git/jirislaby/linux', 'next_master'])
    atexit.register(child.wait)

    stat = repo.status('no')
    if stat:
        raise RuntimeError(f"directory not clean:\n{'\n'.join(stat)}")

    repo.remotes['next'].fetch(callbacks=MyRemoteCallbacks())
    repo.remotes['origin'].fetch(callbacks=MyRemoteCallbacks())

    try:
        run_git_command('rebase', '--onto=next/master', 'korg/next_master', 'devel',
                        capture_output=False, exit_on_error=False)
    except subprocess.CalledProcessError:
        raise RuntimeError("rebase failed")

walker = repo.walk(repo.head.target)
walker.hide(repo.lookup_reference('refs/remotes/next/master').target)
for commit in walker:
    headline = commit.message.partition('\n')[0]
    if headline.startswith('BRANCH_MARKER: '):
        name = headline.removeprefix('BRANCH_MARKER: ')
        repo.branches.local.create(name, commit, force=True)
        print(f"Created branch {name} at {commit.short_id}")

if child:
    print(f"Waiting for PID {child.pid} to finish")
    child.wait()

callbacks = MyRemoteCallbacks()
repo.remotes['korg'].push(['+next/master:refs/heads/next_master',
                           'origin/master:refs/heads/master', '+work:refs/heads/devel'],
                          callbacks=callbacks)
if callbacks.push_failed:
    raise RuntimeError("push failed")
repo.checkout('refs/heads/work')

subprocess.Popen(['make', 'O=../build/bu', 'tags'], start_new_session=True)
