#!/bin/bash
#
# Copyright (C) 2013 Anders Logg and Martin Sandve Alnaes
#
# This file is part of FFC.
#
# FFC is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# FFC is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with FFC. If not, see <http://www.gnu.org/licenses/>.
#
# First added:  2013-04-22
# Last changed: 2013-08-21
#
# This script overwrites the reference data with the current output
# and stores the new reference data as part of the FFC reference data
# repository. The commit id of the stored reference data is commited
# to a file in the main repo.

# Parameters
source ./scripts/parameters

# Get updated reference repository
./scripts/getreferencerepo
if [ $? -ne 0 ]; then
    exit 1
fi

# Check that we have any data
if [ ! -d "$OUTPUT_DIR" ]; then
    echo "Missing data directory '$OUTPUT_DIR'."
    exit 1
fi

# Copy references
echo "Copying new reference data to $DATA_DIR"
rsync -r  --exclude='README.rst' --exclude='*.bin' --exclude='*.cpp' $OUTPUT_DIR/ $DATA_DIR
echo ""

# Get current id for main repo (does not include dirty files, so not quite trustworthy!)
REPO_ID=`git rev-list --max-count 1 HEAD`

# Commit new data to reference repository
pushd $DATA_DIR
git add *
git commit -m "Update reference data, current project head is ${REPO_ID}." | grep -v "create mode"
if [ $? -ne 0 ]; then
    echo "Failed to commit reference data."
    exit 1
fi
DATA_ID=`git rev-list --max-count 1 HEAD`
popd

# Commit reference data commit id to file in main repo
echo $DATA_ID > $DATA_ID_FILE
git commit $DATA_ID_FILE -m"Update reference data pointer to ${DATA_ID}."

# Push references to server
pushd $DATA_DIR
git push
if [ $? -ne 0 ]; then
    echo "WARNING: Failed to push new reference data to server."
fi
popd
