#!/usr/bin/bash
# Commit a change from an svn checkout that was checked out anonymously.
# This is done by temporarily changing the URL to svn+ssh: from svn:
#
# Copyright © 2020–2022 Daniel Fandrich.
# This program is free software; you can redistribute it and/or modify
# Licensed under GNU General Public License 2.0 or later.
# Some rights reserved. See COPYING.

readonly SPEC_TREE="${SPEC_TREE:-.}"
if [[ "$1" != '-m' ]] ; then
    echo Usage: "$0" -m comment file_in_repo '[file2_in_repo...]'
    exit
fi
shift
COMMENT="$1"
shift

# Holds the last file that caused an error
FAILFILE=

for f in "$@"; do
    case "$f" in
        /*) D="$(dirname "$f")";;               # absolute path
        *) D="$(readlink -f "$SPEC_TREE/$f")";; # bare repo name
    esac
    echo "$D"
    cd "$D" || {
        echo Error: could not cd "$D";
        FAILFILE="$f"
        continue;
    }
    OLDU="$(svn info --show-item url)"
    NEWU="$(sed 's/^svn:/svn+ssh:/' <<<"$OLDU")"
    if [[ -z "$OLDU" || "$OLDU" == "$NEWU" ]]; then
        echo Error: URL could not be converted at "$D" 1>&2
        FAILFILE="$f"
    else
        if svn relocate "$OLDU" "$NEWU" &&
            svn ci -m "${COMMENT}"; then
            # Successful submission; clean up & update
            svn relocate "$NEWU" "$OLDU" &&
                svn up
        else
            # Failed submission; clean up only
            echo Failed svn commit 1>&2
            FAILFILE="$f"
            svn relocate "$NEWU" "$OLDU"
        fi
    fi
done
if [[ -n "$FAILFILE" ]]; then
    echo "Error: at least one error occurred, most recently for $FAILFILE" 1>&2
    exit 1
fi
