#!/bin/sh

# NAME:
#	mkdiff - generate diff and template log message
#
# SYNOPSIS:
#	mkdiff [options] [token] [path ...]
#
# DESCRIPTION:
#	This script will capture a diff named
#	$COMMIT_LOGS/$token.diff
#	and a template log message in $COMMIT_LOGS/$token$COMMIT_LOG_EXT
#
#	If no "token" is supplied we just capture the diff in
#	d%Y%m%d (or whatever MKDIFF_DATE_FMT is set to).
#
#	Options:
#
#	-C "dir"
#		chdir to "dir" before starting.
#		This is handy when $SB contains bits from multiple
#		repositories and even SCMs.
#
#	-f "log"
#		Allow override of MKDIFF_DATE_FMT when not using "token".
#
#	-q	suppress '?' lines
#
#	-N	show new files (CVS only)
#
# SEE ALSO:
#	commit-sb(1)
#
# AUTHOR:
#	Simon J. Gerraty <sjg@crufty.net>

# RCSid:
#	$Id: mkdiff,v 1.13 2026/04/30 04:51:42 sjg Exp $
#
#	@(#) Copyright (c) 2020-2025 Simon J. Gerraty
#
#	SPDX-License-Identifier: BSD-2-Clause
#      
#	Please send copies of changes and bug-fixes to:
#	sjg@crufty.net
#

MYNAME=mkdiff

# some defaults
MKDIFF_DATE_FMT=d%Y%m%d

Mydir=`dirname $0`
. $Mydir/hooks.sh

# eval_args will call this for unrecognized options
opt_unknown=mkdiff_options
# rc files can add to mkdiff_options_hooks 
add_hooks mkdiff_options_hooks _unknown_opt
mkdiff_options() {
    run_hooks mkdiff_options_hooks LIFO "$@"
}

__fmt() {
    MKDIFF_DATE_FMT=$1
}

__template() {
    COMMIT_LOG_TEMPLATE=$1
}


long_opt_str="
__fmt:f
__doc:f
__help:f
__template:f
"

# some scm diffs take -x flags
opt_str=C:f:Nqx.

# mk will set SB_TOOLS
. $Mydir/mk
. $SB_TOOLS/eval_args.sh

# do this before we read in scm-funcs.sh
test -z "$opt_C" || 'cd' $opt_C || exit 1

. $SB_TOOLS/scm-funcs.sh
. $SB_TOOLS/commit-funcs.sh


if [ $# -eq 0 ]; then
    log=${opt_f:-`date "+$MKDIFF_DATE_FMT"`}
    scm_diff > $log
    echo $log
    exit 0
fi
token=$1; shift
set_cl_parts $token

mkdiff_log_template() {
    if [ ! -s $cl_log ]; then
        if [ -s ${COMMIT_LOG_TEMPLATE:-/dev/null} ]; then
            sed $MKDIFF_LOG_SEDS $COMMIT_LOG_TEMPLATE > $cl_log
        else
            cat << EOF > $cl_log

PR: $PR
Reviewed by:
EOF
        fi
    fi
    echo Do not forget to edit $cl_log
}

filter_diff() {
    case "$opt_q" in
    "") cat;;
    *) grep -v '^?';;
    esac
}

add_hooks mkdiff_log_var_hooks validate_log_var
validate_log_var() {
    : var=$var,val=$val
    case "$var,$val" in
    PR,[1-9]*[0-9]) ;;
    PR,*) PR= val=;;
    esac
    :
}

mkdir -p `dirname $cl_diff`
if [ ! -s $cl_log ]; then
    for var in PR USER $MKDIFF_LOG_VAR_LIST
    do
        eval "val=\$$var"
        # any of these hooks can set val=
        # if it is not a valid/expected value for $var
        run_hooks mkdiff_log_var_hooks
        test -n "$val" || continue
        MKDIFF_LOG_SEDS="$MKDIFF_LOG_SEDS -e 's,%${var}%,$val,'"
    done
    run_hooks mkdiff_log_template_hooks
    mkdiff_log_template
fi
scm_diff $opt_x $opt_N "$@" | filter_diff > $cl_diff
echo $cl_diff
