#!/bin/sh
#
# Scan the CVS repository and generate a sorted list of commits
# and a binary-search-friendly list of hexadecimal commit timestamps
#
# Copyright (c) 2008-2021 Andreas Gustafsson.  All rights reserved.
# Please refer to the file COPYRIGHT for detailed copyright information.
#

rcsdates="/usr/pkg/libexec/rcsdates"
libpydir="/usr/pkg/lib/bracket/py"
python="/usr/pkg/bin/python3.13"

case $# in
    1) ;;
    *) echo "usage: getdate.sh config" 2>&1; exit 1 ;;
esac

# Read configuration
. "$1"

: ${repo_modules:=src}
: ${branch:=HEAD}

case "`uname -s`" in
    # According to NetBSD sort(1), -H should be specified when
    # sorting files larger than 60 MB
    *NetBSD*) sort="sort -H" ;;
    *) sort="sort" ;;
esac

incremental=true

# rsync.log can be missing if we started out by downloading a repo
# tarball instead, for example on EC2
if
    ! test -f $db_dir/rsync.log ||
    ! test -f $db_dir/commits.$branch
then
    incremental=false
fi

(
    cd "$repo_root"
    if $incremental
    then
	# Extract a list of changed repository files from the rsync log
        $python $libpydir/new_lines.py $db_dir/rsync.log rsync.log.offset.$branch |
            sed -n -e 's!..../../.. ..:..:.. \[[0-9]*\] >f......... \(.*\)$!\1!p' | tr '\n' '\000'
    else
	# Generate a list of all the files in the repository
        IFS=,
	for module in $repo_modules
	do
	     find $module -name '*,v' -print0
	done
	unset IFS
    fi |
    # Extract the commit dates for each file
    $rcsdates $branch
) |
$sort |
if $incremental
then
    # Merge the commits from the updated rcs files with the existing ones
    cat >$db_dir/commits.$branch.inc
    $sort -m -u $db_dir/commits.$branch $db_dir/commits.$branch.inc
else
    cat
fi |
tee $db_dir/commits.$branch.new |
PYTHONPATH=$libpydir $python $libpydir/vc/xcvs/cluster.py $db_dir/dates.$branch.hex.new $db_dir/offsets.$branch.hex.new &&
{
    rm -f $db_dir/dates.$branch.hex.old $db_dir/commits.$branch.old
    test ! -f $db_dir/dates.$branch.hex || mv $db_dir/dates.$branch.hex $db_dir/dates.$branch.hex.old
    test ! -f $db_dir/offsets.$branch.hex || mv $db_dir/offsets.$branch.hex $db_dir/offsets.$branch.hex.old
    test ! -f $db_dir/commits.$branch || mv $db_dir/commits.$branch $db_dir/commits.$branch.old
    mv $db_dir/dates.$branch.hex.new $db_dir/dates.$branch.hex
    mv $db_dir/offsets.$branch.hex.new $db_dir/offsets.$branch.hex
    mv $db_dir/commits.$branch.new $db_dir/commits.$branch
}
