#!/bin/sh
#
# Filature - SliTaz developer platform
# Copyright (C) 2026 SliTaz GNU/Linux - BSD License, see LICENSE
#
# hg-changegroup - Mercurial hook: hand the pushed changesets to Filature.
#
# Declared once in the server-wide hgrc, so every repository is covered,
# future ones included:
#
#   [hooks]
#   changegroup.filature = /usr/share/filature/hg-changegroup
#
# Mercurial runs it in the repository root, $HG_NODE being the first new
# changeset. It never makes a push fail: whatever happens, it logs to
# syslog and exits 0. A missed push is caught up with fil hg-sync.
#

FIL="${FIL:-/usr/bin/fil}"
# The reference repositories. The hook is declared server-wide, so it also
# runs in the devs' own clones on the server: those are left alone.
REPOS="${FIL_HG_REPOS:-/home/slitaz/repos}"
# Author and description URL-escaped: no RS byte can split a record
TEMPLATE='{node}\n{author|urlescape}\n{date|hgdate}\n{desc|urlescape}\n\x1e\n'
repo="$(basename "$(pwd)")"

log() {
    logger -t filature-hg "$repo: $*" 2> /dev/null
}

case "$(pwd)" in
    "$REPOS"/*) ;;
    *) exit 0 ;;
esac
[ -n "$HG_NODE" ] || { log "no HG_NODE, nothing done"; exit 0; }
[ -x "$FIL" ] || { log "$FIL not found, run fil hg-sync later"; exit 0; }

out="$(HGPLAIN=1 hg log -r "$HG_NODE:" --template "$TEMPLATE" 2> /dev/null |
    "$FIL" hg-in "$repo" 2>&1)"
if [ $? = 0 ]; then
    log "$out"
else
    log "fil hg-in failed, run fil hg-sync later: $out"
fi
exit 0
