#!/bin/sh -e

# sh -e; if git rev-parse failed, exit
topdir=`git rev-parse --show-cdup`

if [ ! -d ${topdir}.git ] || ! [ -e ${topdir}.git/config ]; then
	echo "${topdir}.git/config not found, exiting"
	exit 1
fi

if ! [ -d ${topdir}.gear ] && [ -e ${topdir}.gear-rules ]; then
    mkdir -p ${topdir}.gear/
    git mv -f ${topdir}.gear-rules ${topdir}.gear/rules
fi

if ! [ -d ${topdir}.gear ]; then
	echo "${topdir}.gear not found, exiting"
	exit 1
fi


### TODO save should be done using Remotes.pm ###
remotename='upstream'
if [ -n "$1" ]; then
    remotename="$1"
fi
mkdir -p ${topdir}.gear/upstream
remotesfile=${topdir}.gear/upstream/remotes

if ! grep -q '\[remote "'"$remotename"'"\]' ${topdir}.git/config ; then
	echo "ERROR: Section [remote \"$remotename\"] not found in ${topdir}.git/config."
	echo "Usage:"
	echo "$0 [<remote name>]"
	echo "where <remote name> is the name of the remote section in ${topdir}.git/config."
	echo "<remote name> default is 'upstream'."
	exit 1
fi

if ! grep -E -A2 '\[remote *"'"$remotename"'"\]' ${topdir}.git/config > $remotesfile; then
    echo "[remote \"$remotename\" ] not found in ${topdir}.git/config :("
    exit 1
fi

if [ x"$remotename" != x'upstream' ]; then
    sed -i -e 's,\[remote *"'"$remotename"'"\],[remote "upstream"],' $remotesfile
    if gear-remotes-restore; then
	echo 'Created [remote "upstream"] in ${topdir}.git/config'
	echo "Track upstream remote $(sed -n 's/^.*url *= *//p' $remotesfile)"
    else
	echo "gear-remotes-restore failed. please, report a bug."
	exit 1
    fi
fi

git add $remotesfile

: << __END__

=head1	NAME

gear-remotes-save - create .gear/upstream/remotes file from .git/config

=head1	SYNOPSIS

B<gear-remotes-save>
[I<remotename>]

=head1	DESCRIPTION

B<gear-remotes-save> saves .git/config [I<remotename>] entry
in file I<.gear/upstream/remotes>. By default, I<remotename>
expected to be upstream.

=head1	ARGUMENTS

I<remotename> (optional) -- name of git remote in .git/config

=head1	OPTIONS

none.

=head1	AUTHOR

Written by Igor Vlasenko <viy@altlinux.org>.

=head1	COPYING

Copyright (c) 2014-2021 Igor Vlasenko, ALT Linux Team.

This is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation;
either version 2 of the License, or (at your option) any later version.

=cut

__END__
