#!/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 os
import os.path
import subprocess

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


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

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


@contextlib.contextmanager
def gitmirrorlock(ui, gitmirror):
    lockpath = os.path.join(gitmirror, b'cinnabridge.lock')
    fd = -1
    try:
        fd = os.open(lockpath, os.O_WRONLY|os.O_CREAT)
        try:
            fcntl.flock(fd, fcntl.LOCK_EX|fcntl.LOCK_NB)
        except OSError as e:
            if e.errno == EACCES or e.errno == EAGAIN:
                ui.status(_(b'waiting for Mercurial bridge lock...'))
                t0 = time.time()
                fcntl.flock(fd, fcntl.LOCK_EX)
                t1 = time.time()
                dt = t1 - t0
                ui.status(
                    _(b'Mercurial bridge lock acquired after %f sec' % (dt,)))
            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')

    # 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

    # 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):

        # Send objects and heads first.
        subprocess.call(
            ['git', 'fetch', '-q', 'origin', '+refs/heads/*:refs/heads/*'],
            cwd=gitmirror,
            stderr=subprocess.DEVNULL, # chuck `git cinnabar fetch --tags' note
        )

        # Then send cinnabar tags -- `git fetch --tags' doesn't work for
        # this.
        subprocess.call(
            ['git', 'cinnabar', 'fetch', '--tags'],
            cwd=gitmirror,
            stderr=subprocess.DEVNULL,  # chuck tag update noise
        )
