#!/bin/sh
#
# this script updates exrepo modules.

# Unset GIT_DIR. When invoking hooks Git sets GIT_DIR to ".git" (.git in the current directory),
# which confuses child git processes (especially ones operating on other repos).
unset GIT_DIR

# Update exrepo modules only when the merge does not use --squash option.
if [ "$1" == "0" ]
then
    files=`git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD -- .exrepomodules Integrate/Repository/GitExternalRepositoryManagerList`
    
    if [ -n "${files}" ]
    then
        git exrepo-m init

        git exrepo update
    fi
fi

# If configured, preload the "prebuilt libraries" cache from a local share
if [ "$1" == "0" ]
then
    # USA: \\noa.nintendo.com\ntd\share\projects\n_proj\Siglo\Prebuilt
    # JPN: \\devdatasrv2.ncl.nintendo.co.jp\share-siglo$\ForNXUsers\Prebuilt
    prebuilts=$(git config --path NactPrebuilt.location | tr '\\' '/' 2>/dev/null)
    if [ -n "$prebuilts" -a -r "$prebuilts" ]
    then
        baserev=$(git merge-base origin/HEAD HEAD 2>/dev/null)
        ancestors=$(git config --int NactPrebuilt.ancestors 2>/dev/null)
        if [ -z "$ancestors" ] || [ "$ancestors" -lt "0" ]
        then
            ancestors=100
        fi
        for (( i=0; i<$ancestors; i++ ))
        do
            rev=$(git rev-parse ${baserev}~$i 2>/dev/null)
            if [ -r ${prebuilts}/${rev}/PrebuiltResults.list ]
            then
                haverev=$(cat Integrate/Prebuilt/Revision 2>/dev/null)
                if [ "$haverev" != "$rev" ]
                then
                    echo "[post-merge hook] Preloading Prebuilt library cache..."
                    mkdir -p Integrate/Prebuilt 2>/dev/null
                    cp -vu ${prebuilts}/${rev}/* Integrate/Prebuilt
                    if [ $? -eq 0 ]
                    then
                        echo $baserev > Integrate/Prebuilt/BaseRevision
                        echo $rev > Integrate/Prebuilt/Revision
                    fi
                    echo "[post-merge hook] Done!"
                    break
                fi
            fi
        done
    fi
fi

exit 0
