#!/bin/bash

divider_line='--This line, and those below, will be ignored--'

ask_yn() {
    while true; do
        echo "$@" "(y/n)"
        read yn
        case $yn in
            ([Yy]*) return 0 ;;
            ([Nn]*) return 1 ;;
            (*) echo "Enter yes or no" ;;
        esac
    done
}

SVN_TEMPLATE_MESSAGE=${SVN_TEMPLATE_MESSAGE-}

editor=${SVN_EDITOR:-${EDITOR:-vi}}

type svn &> /dev/null || { echo svn not found; exit -1; }

svn info > /dev/null || { exit $?; } # bail if this is not a working copy

status=0
nocommit=0
workdir=$(mktemp -d /tmp/svn-commit-wrapper.XXXXXX)  # must end in XXXXXX on macOS
templateMessageFile=$workdir/svn-commit-template
messageFile=$workdir/svn-commit
templateLogFile=$templateMessageFile-log
logFile=$messageFile-log
printf "%s\n" "$SVN_TEMPLATE_MESSAGE"  > "$templateMessageFile"
echo "$divider_line" >> "$templateMessageFile"
svn status "$@" >> "$templateMessageFile"
svn diff "$@" >> "$templateMessageFile"
cp "$templateMessageFile" "$messageFile"
$editor "$messageFile"

## delete until divider line
sed -e /"$divider_line"/,'$'d "$messageFile" > "$logFile"
sed -e /"$divider_line"/,'$'d "$templateMessageFile" > "$templateLogFile"
echo >> "$templateLogFile"  # end in newline

if diff -w "$templateLogFile" "$logFile" > /dev/null; then
    echo 'Log message unchanged -- aborting commit.'
    rm -rf "$workdir"
    exit 1
elif ! grep -q -v '^[[:space:]]*$' "$logFile"; then
    echo 'Empty log message -- aborting commit.'
    rm -rf "$workdir"
    exit 1
else
    cat "$logFile"

    echo --
    if ask_yn 'OK to commit?'; then
        svn commit "$@" -F "$messageFile"
        status=$?
        if [[ $status -eq 0 ]]; then
            rm -rf "$workdir"
        else
            echo Commit failed... log message in "$messageFile"
            exit $status
        fi
    else
        rm -rf "$workdir"
        exit 1
    fi
fi
wcroot=$(svn info | sed -n '/Working Copy Root Path/s/Working Copy Root Path: //p')
if ask_yn "Update $wcroot?"; then
    svn update "$wcroot"
    status=$?
    if [[ $status != 0 ]]; then
        echo Update failed
        exit $status
    fi
else
    echo Not updating
fi
