#!/usr/bin/env python3
#
# Copyright (c) 2025 The NetBSD Foundation, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

"""gitmirror is a hook to trigger git fetch in a corresponding git repo.

Usage:
  [netbsd_hooks]
  gitmirror = /git/repo
  [hooks]
  txnclose.gitmirror = python:....gitmirror.hook
"""

import contextlib
import fcntl
import errno
import os
import os.path
import quopri
import subprocess
import time

from mercurial.i18n import _
from mercurial import (
    error,
    pycompat,
    registrar,
)


configtable = {}
configitem = registrar.configitem(configtable)

# [netbsd_hooks]
# gitmirror = /git/repo
configitem(
    b'netbsd_hooks',
    b'gitmirror',
    default=None,
)

# [netbsd_hooks]
# gitmirror_topics = true
configitem(
    b'netbsd_hooks',
    b'gitmirror_topics',
    default=False,
)


# [netbsd_hooks]
# gitmirror_failure_sendmail = /usr/sbin/sendmail -oi admins@example.com
configitem(
    b'netbsd_hooks',
    b'gitmirror_failure_sendmail',
    default=None,
)


@contextlib.contextmanager
def gitumask(ui, gitrepo):
    """Temporarily set umask to match git repository's.

    This should really use the git core.sharedRepository variable, but
    it's simpler to just stat the repo directory than to parse git
    configuration from here.
    """
    mode = os.stat(gitrepo).st_mode & 0o777
    umask = os.umask(-1)
    try:
        # Find the bits in the mode that the current umask _would_
        # clear, with mode & umask -- we don't want to clear those
        # bits, so nix them from umask, with umask & ~(mode & umask).
        os.umask(umask & ~(mode & umask))
        yield
    finally:
        os.umask(umask)


@contextlib.contextmanager
def gitmirrorlock(ui, gitmirror):
    lockpath = os.path.join(gitmirror, b'cinnabridge.lock')
    fd = -1
    try:
        with gitumask(ui, gitmirror):
            fd = os.open(lockpath, os.O_WRONLY | os.O_CREAT, mode=0o666)
        try:
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except OSError as e:
            if e.errno == errno.EACCES or e.errno == errno.EAGAIN:
                ui.status(_(b'waiting for Mercurial bridge lock...\n'))
                t0 = time.time()
                fcntl.flock(fd, fcntl.LOCK_EX)
                t1 = time.time()
                d = t1 - t0
                ui.status(
                    _(b'Mercurial bridge lock acquired after %f sec\n' % (d,)))
            else:
                raise
        yield
    finally:
        if fd != -1:
            os.close(fd)


def hook(ui, repo, hooktype, node=None, **kwargs):
    if hooktype != b'txnclose':
        raise error.Abort(
            _(b'Unsupported hook type %r') % pycompat.bytestr(hooktype)
        )

    gitmirror = ui.config(b'netbsd_hooks', b'gitmirror')
    gitmirror_topics = ui.configbool(b'netbsd_hooks', b'gitmirror_topics')
    gitmirror_failure_sendmail = \
        ui.config(b'netbsd_hooks', b'gitmirror_failure_sendmail')

    # If we're processing a git-push from the mirror already, don't
    # recursively trigger a git-fetch -- the git repo already has
    # everything we would want to get from that.
    if 'TNFREPO_HG_GIT_PUSH' in os.environ:
        return

    # If there's no mirror configured, nothing to do.
    if not gitmirror:
        return

    # If it's not wired up, just don't do anything -- it may be in the
    # process of being created; someone can always retry the sync
    # later.
    if not os.path.isdir(gitmirror):
        return

    # Record a list of failures to deliver by mail to admins.
    #
    # Paranoia: Encode arbitrary byte sequences in reasonable US-ASCII.
    # Should be compatible with unvis(1).
    failures = []

    def escape1(b):
        if b in b'\r':
            return b'\\r'
        if b in b'\t':
            return b'\\t'
        if b in b'\\':
            return b'\\\\'
        if 32 <= b < 0x7f:
            return bytes([b])
        return b'\\%03o' % (b,)

    def escape(bs):
        return b''.join(map(escape1, bs))

    def fail(desc, cmd, p):
        stdout = p.stdout
        if stdout.endswith(b'\n'):
            stdout = stdout[:-1]
            trailing_lf = True
        else:
            trailing_lf = False
        lines = [escape(line) for line in stdout.split(b'\n')]
        ui.warn(b'%s: %s\n' % (desc, b'\n'.join(lines)))
        failures.append((desc, cmd, p.returncode, lines, trailing_lf))

    # Out of paranoia, hold an exclusive lock on the git-cinnabar
    # bridge while we trigger an update.  It's possible this isn't
    # necessary, but concurrent calls to git-fetch are unlikely to be
    # useful, so this probably doesn't hurt performance and may help
    # avoid races.  This also excludes concurrent git-push.  (We can't
    # currently be doing an hg push in the service of git push because
    # of the TNFREPO_HG_GIT_PUSH check above.)
    with gitmirrorlock(ui, gitmirror):

        # We capture git's output (mixing stdout and stderr, probably
        # not a big deal that they're not distinguished), and then
        # report a warning only if it failed (since git-cinnabar is a
        # little unnecessarily noisy sometimes).

        # Send objects and heads first.
        cmd = \
            [b'git', b'fetch', b'-q', b'origin', b'+refs/heads/*:refs/heads/*']
        p = subprocess.run(
            cmd,
            cwd=gitmirror,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
        )
        if p.returncode != 0:
            fail(_(b'git mirror content failed'), cmd, p)
            # XXX send notification mail

        # If requested, send draft objects and heads.  We don't have
        # any notion of draft tags.
        if gitmirror_topics:
            cmd = [
                b'git', b'fetch', b'-q', b'draft',
                b'+refs/heads/topics/*:refs/namespaces/draft/refs/heads/*',
            ]
            p = subprocess.run(
                cmd,
                cwd=gitmirror,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
            )
            if p.returncode != 0:
                fail(_(b'git mirror topics failed'), cmd, p)

        # Then send cinnabar tags -- `git fetch --tags' doesn't work for
        # this.
        cmd = [b'git', b'cinnabar', b'fetch', b'--tags']
        p = subprocess.run(
            cmd,
            cwd=gitmirror,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
        )
        if p.returncode != 0:
            fail(_(b'git mirror tags failed'), cmd, p)

    # If anything went wrong, send mail to admins.
    #
    # XXX Too bad Python doesn't expose whether there's a core dump or
    # not!
    if failures and gitmirror_failure_sendmail:
        header = [
            b'Subject: hg->git mirror push failure',
            b'Content-Type: text/plain; charset=us-ascii',
            b'Content-Transfer-Encoding: quoted-printable',
        ]
        body = b''
        body += b'Hg repository: %s\n' % (repo.origroot,)
        body += b'Git repository: %s\n' % (gitmirror,)
        body += b'\n'
        body += b'\n'.join(
            b'%s with status %d:\n\n  $ %s\n%s\n%s' % (
                desc,
                returncode,
                b' '.join(cmd),  # XXX quote
                b'\n'.join(b'  ' + line for line in lines),
                b'' if trailing_lf else b'(no trailing newline)\n',
            )
            for (desc, cmd, returncode, lines, trailing_lf) in failures
        )
        mail = b'%s\n\n%s' % (
            b'\n'.join(header),
            quopri.encodestring(body, quotetabs=False),
        )
        p = subprocess.run(
            gitmirror_failure_sendmail,
            shell=True,
            cwd=gitmirror,
            input=mail,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
        )
        if p.returncode != 0:
            ui.warn(
                _(b'failed to report error to admins, status %d: %s\n') %
                (p.returncode, p.stdout)
            )
