#!/bin/bash

# Copyright (c) 2012, NVIDIA CORPORATION
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#  * Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#  * Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#  * Neither the name of NVIDIA CORPORATION nor the names of its
#    contributors may be used to endorse or promote products derived
#    from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


#
# This script sync's NVIDIA's version of the 3rdparty u-boot.git repo
# from nv-tegra, NVIDIA's public git repository, to the exact commit
# ID that the binary u-boot shipped was built from. This allows
# replication of the exact u-boot build.
#

# verify that git is installed
if  ! which git > /dev/null  ; then
	echo "ERROR: git is not installed. If your linux distro is 10.04 or later,"
	echo "git can be installed by 'sudo apt-get install git-core'."
	exit
fi

LDK_UBOOT_DIR=$(cd `dirname $0` && pwd)
LDK_USOURCE_DIR=${LDK_UBOOT_DIR}/uboot_source

if [ -d "${LDK_USOURCE_DIR}" ] ; then
	echo "ERROR: ${LDK_USOURCE_DIR} already exists!"
	exit
fi

TAG=
if [ ! -z "$1" ]; then
	TAG=$1
else
	while [ -z "${TAG}" ]; do
		echo -n "Please enter a tag to sync u-boot source to: "
		read TAG
	done
fi

echo "Downloading u-boot source..."
git clone git://nv-tegra.nvidia.com/3rdparty/u-boot.git -n ${LDK_USOURCE_DIR}
if [ $? -ne 0 ]; then
	echo "U-boot sources sync failed!"
	exit 1
fi

pushd ${LDK_USOURCE_DIR} > /dev/null
git tag -l | grep -q "$TAG"
if [ $? -eq 0 ]; then
	echo "Syncing up with tag $TAG..."
	git checkout -b mybranch_$(date +%Y-%m-%d) ${TAG}
	popd > /dev/null
	echo ""
	echo "U-boot sources sync'ed successfully!"
else
	echo "Tag $TAG could not be founding, cleaning up..."
	popd > /dev/null
	rm -rf ${LDK_USOURCE_DIR}
	echo ""
	echo "U-boot sources sync failed!"
	exit 2
fi
