#!/bin/bash

# 
# VMWare Multiple Device Tricks =)
# alias the multi-connected devices
# 
# Example:
#   alias adb1='adb -s 192.168.123.131'
#   alias adb2='adb -s 192.168.123.132'

# allow aliases to be created in "interactive shells"
shopt -s expand_aliases

PARAM1=$1
PARAM2=$2

usage() {
  echo
  echo "  *** MUST BE SOURCED for aliases to take effect in your current shell ***"
  echo
  echo "  source adbnet.sh  192.168.123.13"
  echo "  .      adbnet.sh  192.168.123.12   (\".\" is same as source"
  echo "                   xxx.xxx.xxx.xx#  (remove the last digit"
  echo 
  echo "  Aliases generated:"
  echo "    alias adb1=\"adb -s 192.168.123.131\""
  echo "    alias adb2=\"adb -s 192.168.123.132\""
  echo "    alias adb3=\"adb -s 192.168.123.133\""
  echo "    alias adb4=\"adb -s 192.168.123.134\""
  echo "    alias adb5=\"adb -s 192.168.123.135\""
  echo "    alias adb6=\"adb -s 192.168.123.136\""
  echo "    alias adb7=\"adb -s 192.168.123.137\""
  echo "    alias adb8=\"adb -s 192.168.123.138\""
  echo "    alias adb9=\"adb -s 192.168.123.139\""
  echo
  echo "  \"-f\":  defaults to test mode for saftey, use \"-f\" to execute"
  echo "  . adbnet.sh  192.168.123.12  -f"
  echo

  # cannot exit if sourced with local environment...will exit the shell
  # exit 1
}

echo_error() {
	echo "***"
	echo "*** ERROR:  $1"
	echo "***"
}

#!/bin/bash

# Test an IP address for validity:
# Usage:
#      valid_ip IP_ADDRESS
#      if [[ $? -eq 0 ]]; then echo good; else echo bad; fi
#   OR
#      if valid_ip IP_ADDRESS; then echo good; else echo bad; fi
#
function valid_ip()
{
    local  ip=$1
    local  stat=1

    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
            && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
        stat=$?
    fi
    return $stat
}

create_adb_aliases() {
  if [[ -n $PARAM2 ]]; then
  	if [ $PARAM2 == "-f" ]; then
		  set -x
		  for NUM in $(seq 1 9)
		  do
		  	# `alias adb$NUM=\"adb -s $PARAM1$NUM\"`
		  	alias adb${NUM}="adb -s ${PARAM1}${NUM}"
		  	# alias "adb${NUM}=adb -s ${PARAM1}${NUM}"
      	# alias "adb${NUM}"="\`adb -s ${PARAM1}${NUM}\`"
      done
		  set +x
  	else
  		echo_error "-f  needs to be second parameter to force the execution"
  	fi
  else
  	echo "*************************************"
  	echo "    This is what will be generated:"
  	echo "    (use \"-f\" if this is correct to force execute)"
  	echo "*************************************"
	  for NUM in $(seq 1 9)
	  do
	  	echo "  alias adb$NUM=\"adb -s ${PARAM1}${NUM}\""
	    # echo "adb${NUM}=adb -s ${PARAM1}${NUM}"
	  done
  fi

}


main () {
  if [[ -n $PARAM1 ]]; then
    if valid_ip $PARAM1; then
    	create_adb_aliases
    else
    	echo_error "not a valid IP address"
    fi
  else
  	usage
  fi
}


main


