#!/usr/local/bin/bash
#set -x
#export PS4='\e[90m+${LINENO} in ${#BASH_SOURCE[@]}>${FUNCNAME[0]}:${BASH_SOURCE[@]##*/} \e[0m'

if [ "$_INIT" = "done" ]; then
  #echo "already inititalized"
  return 0
fi
if [ -z "$current" ]; then
  current="$this"
fi

len=${#BASH_LINENO[@]}
depth=1

current.context()
{
  current=${BASH_SOURCE[0]}
  if [ -z "${FUNCNAME[0]}" ]; then
        depth=len
        ((depth-=2))
        echo depth=$depth
  fi

  Current=$(which $current)
  if [ -z "$Current" ]; then
    Current=$(which ./$current)
  else
    CURRENT=$(readlink -f $Current)
  fi
  current=$(basename $Current)

  Caller=${BASH_SOURCE[$depth+1]}
  if [ -n "$Caller" ]; then
    CALLER=$(readlink -f $Caller)
    caller=$(basename $Caller)
  else
    caller=""
  fi

  DIR=$(dirname $CURRENT)
}

this.mode() # checks if sourced
{
  #this.status
  if [ "${FUNCNAME[$depth]}" = "main" ]; then
    echo "starting $CURRENT"
    return 0
  else
    echo "sourcing $DIR/$current from $CALLER" 
    return 1
  fi

  # if [ -z "$caller" ]; then
  #   caller="this"
  # fi

  # startFunc="$caller.start"
  # this.functionExists $startFunc
}

this.functionExists()
{

  local startFunc="$1"
  shift
  RETURN=$1

  if [ "$(type -t $startFunc)" = "function" ]; then
    echo "$startFunc exists"
    return 0
  else
    echo "$startFunc does not exist"
    return 1
  fi  
}


this.status() {
  echo "\$0: $0"
  echo "\$Current: $Current"
  echo "\$current: $current"
  echo "\$Caller: $Caller"
  echo "\$caller: $caller"
  echo "\$this: $this"
  echo "\$BASH_COMMAND: $BASH_COMMAND"
  echo "Functions: ${FUNCNAME[@]}"
  echo "bash lineno: ${BASH_LINENO[@]}"
  echo "bash source: ${BASH_SOURCE[@]}"
  echo ""
  echo "current   Functions: ${FUNCNAME[$depth]}"
  echo "current bash source: ${BASH_SOURCE[$depth]}"
}

# this.mode
# exit 0

current.context
if (this.mode); then
 echo "starting configured shell at level $SHLVL"
 bash
 if [ "$SHLVL" = "0" ]; then
   echo "bottom reached...do not exit last bash"
 fi
#else
#  echo "just sourcing init from $CURRENT"
fi

if (this.functionExists step) ; then
  warn.log "debug was already sourced"
else
  echo "sourcing $DIR/debug from $current"
  #export _SET_="-x"
  source $DIR/debug
  success.log "debug sourced"
  current.context
  #this.status

  export _INIT="done"

  if [ -z "$CONFIG" ];then
    CONFIG=$($DIR/config file)
    echo "config found: $CONFIG"
  fi
  success.log "config loaded"
fi
