#!/bin/bash

# Function:
# Check that ./build_tree link points to the build tree of actual branch and possibly fix this.
# Ends with error code 1 when link has been changed.
#
# This script assumes it is started from root directory of the source tree.


# get standard parameters
PREVIOUS_HEAD=$1                # hash
NEW_HEAD=$2                     # hash
BRANCH_CHECKOUT_FLAG=$3         # 1-checkout branch / 0-checkout file

if [ -n "${PREVIOUS_HEAD}" -a -n "${NEW_HEAD}" ]
then
  CALLED_AS_HOOK=1
fi


NEW_BRANCH=`git rev-parse --abbrev-ref HEAD`
BUILD_DIR=${FLOW123D_BUILD_DIR:-`pwd`/build-${NEW_BRANCH}}

if [ ! -d build_tree ]
then
    ln -s ${BUILD_DIR} build_tree
fi
LS=`ls -l build_tree`
BUILD_TREE=${LS##* -> }
OLD_BRANCH=${BUILD_TREE##*/build-}


echo ""
echo "POST-CHECKOUT(${OLD_BRANCH} -> ${NEW_BRANCH}):"

# check that we have build directory
if [ ! -d ${BUILD_DIR} ]
then
    mkdir -p ${BUILD_DIR}
    
#    if [ -n CALLED_AS_HOOK -a  ! "${OLD_BRANCH}" == "${NEW_BRANCH}"  ]
#    then
#        if [ -d build_tree ]
#        then
#            echo "Possibly new branch, copy build tree from the previous one."
#            cp -r build_tree/* ${BUILD_DIR}  
#        fi
#    fi    
fi

# check that we have correct link
if [ ! "${OLD_BRANCH}" == "${NEW_BRANCH}" ]
then 
    echo "setting build_tree -> ${BUILD_DIR}"
    rm -f build_tree
    ln -s ${BUILD_DIR} build_tree
    
    if [ ! -n CALLED_AS_HOOK ]
    then
        echo "Updating build_tree link stops the build. Please, run it again."
        exit 1
    fi
fi  

exit 0
