#!/bin/sh -e

if [ ! -d .gear ]; then
	echo "This directory does not contain .gear directory, exiting"
	exit 1
fi
if [ ! -d .git ] || ! [ -e .git/config ]; then
	echo "This directory does not contain .git/config, exiting"
	exit 1
fi

### TODO save should be done using Remotes.pm ###

remotename='upstream'
if [ -n "$1" ]; then
    remotename="$1"
fi
mkdir -p .gear/upstream

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

if ! egrep -A2 '\[remote *"'"$remotename"'"\]' .git/config > .gear/upstream/remotes; then
    echo "[remote \"$remotename\" ] not found in .git/config :("
    exit 1
fi

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