# Common functions

function find_program(){
    _name=$1
    shift
    _cmd=`which $_name 2>/dev/null`
    if [[ -z "$_cmd" ]];then
        for p in $@;do
	    if [[ -x "$p/$_name" ]];then
	        _cmd=$p/$_name
  	        break
            fi
        done
    fi

    if [[ -z "$_cmd" ]];then
        echo "Fail to find executable : $_name" > /dev/stderr
        exit -2
    fi
    echo "$_cmd"
}

function cache_output_and_update(){
    cacheFile=$1; shift
    expiryTime=$1; shift
    outputCommand="$@"
    if [ "$LOCAL_CACHE" = "1" ];then
	if [ ! -e $LOCAL_CACHE_DIR ];then
	    mkdir -p $LOCAL_CACHE_DIR
	fi
	if [ ! -e ${cacheFile} ];then
	    ${outputCommand} | tee "${cacheFile}"
	else
	    fileTime=`stat --format '%Y' "${cacheFile}"`
	    currentTime=`date '+%s'`
	    if expr "$fileTime" "+" "$expiryTime" "<" "$currentTime" >/dev/null; then
		    ${outputCommand} | tee "${cacheFile}"
	    else
		    cat "${cacheFile}"
	    fi
	fi
    else
	${outputCommand}
    fi
}


