#!/bin/bash

export SCRIPT_DIR=$(dirname "$0")

##
## Configuration Variables
##

config ()
{
    # A whitespace-separated list of executables that must be present and locatable.
    : ${REQUIRED_TOOLS="xctool"}
    
    export REQUIRED_TOOLS
}

##
## Bootstrap Process
##

main ()
{
    config

    if [ -n "$REQUIRED_TOOLS" ]
    then
        echo "*** Checking dependencies..."
        check_deps
    fi

    local submodules=$(git submodule status)
    local result=$?

    if [ "$result" -ne "0" ]
    then
        exit $result
    fi

    if [ -n "$submodules" ]
    then
        echo "*** Updating submodules..."
        update_submodules
    fi
}

check_deps ()
{
    for tool in $REQUIRED_TOOLS
    do
        which -s "$tool"
        if [ "$?" -ne "0" ]
        then
            echo "*** Error: $tool not found. Please install it and bootstrap again."
            exit 1
        fi
    done
}

bootstrap_submodule ()
{
    local bootstrap="script/bootstrap"

    if [ -e "$bootstrap" ]
    then
        echo "*** Bootstrapping $name..."
        "$bootstrap" >/dev/null
    else
        update_submodules
    fi
}

update_submodules ()
{
    git submodule sync --quiet && git submodule update --init && git submodule foreach --quiet bootstrap_submodule
}

export -f bootstrap_submodule
export -f update_submodules

main
