#!/bin/bash

# Author: Justin Moore
# Version: 0.2.0

#connection testing settings
pingcmd="ping -q -c 1"
site="google.com"

#notification settings
sound_player="espeak"
player_opts=("-v en-uk-north")
sound_file=""
sound_message="The internet is working!"
popup_box="false"
play_sound="true"

#Script Functions
loop_script="true"


################################################################################
## DO NOT CHANGE ANYTHING BEYOND THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING ##
################################################################################


withLoop(){
  while true; do


    clear
    echo

    echo "Pinging: ${site}"
    ${pingcmd} ${site} &>/dev/null
    if [ $? = "2" ];then
      echo
      echo "The internet is not working:("
      sleep 1

    elif [ $? = "1" ];then
      if [ "${play_sound}" = "true" ];then
        ${sound_player} ${player_opts[*]} ${sound_file} "${sound_message}" &
      fi

      lanip=$(ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')
      pubip=$(curl -s http://whatismijnip.nl |cut -d " " -f 5)

      clear
      echo "Yay! The internet is working! :)"
      echo
      echo " ====================="
      echo "|  Connection Info    |"
      echo " ====================="
      echo

      echo "Local IP Address: ${lanip}"

      echo
      echo "External IP Address: ${pubip}"

      echo

      if [ "${popup_box}" = "true" ];then
        zenity --info --text="Ping to '${site}' successful!" &>/dev/null
      fi

      exit 0;

    fi
  done

}

withoutLoop(){

    clear
    echo

    echo "Pinging ${site}"
    ${pingcmd} ${site} &>/dev/null

    if [ $? = "2" ];then
      echo
      echo "The internet is not working :("

    elif [ $? = "1" ];then

      if [ "${play_sound}" = "true" ];then
        ${sound_player} ${player_opts} ${sound_file} "${sound_message}" &
      fi



      lanip=$(ifconfig | sed -En 's/127.0.0.1//;s/.*inet (addr:)?(([0-9]*\.){3}[0-9]*).*/\2/p')
      pubip=$(curl -s http://whatismijnip.nl |cut -d " " -f 5)

      clear

      echo "Yay! The internet is working! :)"
      echo
      echo " ====================="
      echo "|  Connection Info    |"
      echo " ====================="
      echo
      echo "Local IP Address: ${lanip}"

      echo
      echo "External IP Address: ${pubip}"

      echo

      if [ "${popup_box}" = "true" ];then
        zenity --info --text="Ping to '${site}' successful!" &>/dev/null
      fi

      exit 0;

    fi

}

if [ "${loop_script}" = "true" ];then
  withLoop
else
  withoutLoop
fi