#!/bin/sh

LC_ALL=POSIX;
export LC_ALL

# Returns an error once a command returns an error
set -e

DRY_RUN=
QUIET=--quiet

if [ "x$1" = "x--dry-run" -o "x$1" = "x-n" ]; then
    DRY_RUN=--dry-run
    shift
fi

if [ -n "DRY_RUN" ]; then
    QUIET=
fi

if [ -d "$1/.git" ]; then
    pushd "$1" > /dev/null
    branch=`git rev-parse --abbrev-ref HEAD`
    remote=`git config branch.${branch}.remote`
#    echo "Git repository, in branch '$branch'"
    git fetch $DRY_RUN $QUIET -p --all
    [ -z "$DRY_RUN" ] && git reset $QUIET --hard "$remote/$branch"
    git clean $DRY_RUN $QUIET -f -d -x

    ln -s -n -f "$1" $HOME/latest-internal-release-branch

    # Hard-reset integration "every day", if today's "$branch" is integration
    # and create testsuite-Monday, testsuite-Tuesday, and so on...
    if [ x"$branch" = "xintegration" ]; then
        git push $DRY_RUN $QUIET -f cgal-dev "$remote/$branch:refs/heads/`date '+testsuite-%A'`" cgal/master:integration
    elif [ x"$branch" = "xintegration-4.5" ]; then
        git push $DRY_RUN $QUIET -f cgal-dev "$remote/$branch:refs/heads/`date '+testsuite-%A'`" cgal/releases/CGAL-4.5-branch:integration-4.5
    else
        git push $DRY_RUN $QUIET -f cgal-dev "$remote/$branch:refs/heads/`date '+testsuite-%A'`"
    fi

    popd > /dev/null
else
    svn up "$1"
fi

# Update the candidates branch, if any.
[ -d "$2" ] && svn up "$2"

# Update the symbolic links, using $1 and $2
rm "$HOME/CGAL/last-release-branch"

ln -s "$1" "$HOME/CGAL/last-release-branch"

## That was for LaTeX documentation
#rm "$HOME/CGAL/last-manual_tools-branch"
#rm "$HOME/CGAL/last-manual-branch"


## That was for LaTeX documentation
# # Search the Manual and Manual_tools package in candidates, if any.
# # Else use the main branch.
# if [ -d "$2" -a -d "$2/Manual_tools" ]; then
#   ln -s "$2" "$HOME/CGAL/last-manual_tools-branch";
# else
#   ln -s "$1" "$HOME/CGAL/last-manual_tools-branch";
# fi
# if [ -d "$2" -a -d "$2/Manual" ]; then
#   ln -s "$2" "$HOME/CGAL/last-manual-branch";
# else
#   ln -s "$1" "$HOME/CGAL/last-manual-branch";
# fi

## That was for LaTeX documentation
# # Update the manual tools
# # They are used in create_new_release to build the installation manual.
# "$HOME/bin/update_manual_tools"

# Launch create_new_release, from the branch itself
[ -z "$DRY_RUN" ] && exec "$HOME/CGAL/last-release-branch/Scripts/developer_scripts/create_new_release" --no-scm-update "$@"
#                       --no-scm-update because branches have already been updated
