#!/system/bin/sh

# -----------------------------------------------------------------------------
# define constants
#
__TRUE=0
__FALSE=1

# -----------------------------------------------------------------------------
#
# the environment variable MODPATH is only defined by Magisk for the script customize.sh
#
[ "${MODPATH}"x = ""x ] && MODPATH="${0%/*}"

MODULE_NAME="$( grep "^id=" ${MODPATH}/module.prop  | cut -f2 -d "=" )"
[ "${MODULE_NAME}"x = ""x ] && MODULE_NAME="unknown_magisk_module"


# -----------------------------------------------------------------------------
#
SCRIPT_NAME="${0##*/}"

SCRIPT_DIR="${0%/*}"

# -----------------------------------------------------------------------------
# change either "0 = 1" to "0 = 0" in this script or create the file /data/local/tmp/debug to enable the debug output to the log file
#
if [ 0 = 1 -o -r /data/local/tmp/debug ] ; then
  LOGFILE="/data/local/tmp/${MODULE_NAME}_${SCRIPT_NAME}.log"

#  echo "Writing all messages to the log file ${LOGFILE}"

  exec 1>"${LOGFILE}" 2>&1

  if [ -r /data/local/tmp/trace ] ; then
    set -x
  fi
fi

# -----------------------------------------------------------------------------

START_ADB_WIFI="${SCRIPT_DIR}/system/bin/start_adb_via_wifi.sh"


echo "Waiting for the network ..."

# wait up to 30 seconds for the network
#
NETWORK_WAIT_TIMEOUT=30
i=0
while [ $i -lt ${NETWORK_WAIT_TIMEOUT} ] ; do

  CUR_IP_ADDRESS="$(  ifconfig -a | grep "inet " | grep -v 127.0.0 | awk '{ print $2 }' | cut -f2 -d ":"  )"
  if [ "${CUR_IP_ADDRESS}"x = ""x ] ; then
    CUR_IP_ADDRESS="$( ip addr list | grep "inet " | grep -v 127.0.0 | awk '{ print $2 }' | cut -f1 -d "/" )"
  fi
  if [ "${CUR_IP_ADDRESS}"x = ""x ] ; then
    sleep 1
    let  i=i+1 
  else
    echo " ... found an IP: ${CUR_IP_ADDRESS}"
    echo "The network is ready after $i seconds"
    break    
  fi
done            


if [ -r  "${START_ADB_WIFI}" ] ; then
  eval $( grep "^DATA_DIR=" "${START_ADB_WIFI}" )
  eval $( grep "^DISABLE_SOCAT_RESTART_SEMFILE="  "${START_ADB_WIFI}" )

  if [ "${DISABLE_SOCAT_RESTART_SEMFILE}"x != ""x ] ; then
    if [ -r  "${DISABLE_SOCAT_RESTART_SEMFILE}" ] ; then
      echo "Deleting the file \"${DISABLE_SOCAT_RESTART_SEMFILE}\" "
      rm -f "${DISABLE_SOCAT_RESTART_SEMFILE}"
    fi
  fi
  echo "Starting \"${START_ADB_WIFI}\" ..."
  sh "${START_ADB_WIFI}"
else
  echo "ERROR: ${START_ADB_WIFI} not found"
fi
