#!/bin/bash
#
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

set -eu

# This is a cheap mr/cm-alike. Perhaps we should use mr/cm.

TOOLS="https://git.openstack.org/openstack/diskimage-builder https://git.openstack.org/openstack/tripleo-image-elements https://git.openstack.org/openstack/tripleo-heat-templates https://git.openstack.org/openstack/tripleo-incubator https://git.openstack.org/openstack-infra/tripleo-ci https://git.openstack.org/openstack/os-cloud-config"

ZUUL_REF=${ZUUL_REF:-''}

if [ -n "$ZUUL_REF" ]; then
    echo "SKIPPING pull-tools as ZUUL_REF is present."
    exit 0
fi

for TOOL in $TOOLS; do
    TOOL_BASE=$(basename $TOOL)
    echo pulling/updating $TOOL_BASE
    LOCATION_OVERRIDE=DIB_REPOLOCATION_${TOOL_BASE//[^A-Za-z0-9]/_}
    LOCATION=${!LOCATION_OVERRIDE:-$TOOL}
    REF=master
    REF_OVERRIDE=DIB_REPOREF_${TOOL_BASE//[^A-Za-z0-9]/_}
    REF=${!REF_OVERRIDE:-$REF}
    if [ ! -d $TRIPLEO_ROOT/$TOOL_BASE ] ; then
        cd $TRIPLEO_ROOT
        git clone $LOCATION
        pushd $TOOL_BASE
        git checkout $REF  # for a branch or SHA1
        popd
    else
        cd $TRIPLEO_ROOT/$TOOL_BASE
        if echo "/$(git symbolic-ref -q HEAD)" | grep -q "/${REF}\$" ; then
            if ! git pull --ff-only ; then
                    echo "***************************************************"
                    echo "* Perhaps you want to 'git rebase origin/$REF'? *"
                    echo "***************************************************"
                    exit 1
            fi
        else
            echo "***************************************"
            echo "* $TOOL_BASE is not on branch $REF; skipping pull *"
            echo "***************************************"
        fi
    fi
    echo -n $TRIPLEO_ROOT/$TOOL_BASE:
    cd $TRIPLEO_ROOT/$TOOL_BASE
    git --no-pager log -1 --pretty=oneline
done
