#!/usr/bin/env bash
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#                                                                               #
#       Hurricane Electric Tunnel Broker IP Parser                              #
#       Writen by: RBS                                                          #
#       Version: 0.5          Released: 20.03.2018                              #
#                                                                               #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#                                                                               #
#     Usage: ./get_hetb_fastest_ip.sh  username  &  wait for password prompt    #
#                                                                               #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
__green() {
    printf '\033[1;31;32m'
    printf -- "%b\\n" "$1"
    printf '\033[0m'
}
__red() {
    printf '\033[1;31;40m'
    printf -- "%b\\n" "$1"
    printf '\033[0m'
}
__yellow() {
    printf '\033[1;33;40m'
    printf -- "%b\\n" "$1"
    printf '\033[0m'
}

if [[ -z $1 ]] ;then
    echo 
    __red "VARIABLES ARE NOT SET!!!"
    echo
    __yellow "usage $0 USERNAME & wait for password prompt"
    echo 
  exit 2
fi
# Check if the curl installed .
if [ ! -x /usr/bin/curl ] ; then
    command -v curl >/dev/null 2>&1 || { echo >&2 "Please install curl or set it in your path. Aborting."; exit 1; }
fi
_login=$1
read -r -s -p "Password for $_login: " _pass 
echo 
echo "________________________"
echo 

if [[ -z $_pass ]]; then 
    __red "Please provide your https://tunnelbroker.net/ password"   
    echo 
  exit 2
fi

# Variables
_progname=rbs
_cookie=$(mktemp --tmpdir="/tmp" -t ${_progname}_cookie_***XXXX)
_output=$(mktemp --tmpdir="/tmp" -t ${_progname}_output_***XXXX)
_ua="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:59.0) Gecko/20100101 Firefox/59.0"
_null="> /dev/null 2>&1"
_url="https://tunnelbroker.net/login.php"
_url_1="https://tunnelbroker.net/new_tunnel.php"
_grep="grep icmp_"
_ping="ping -n -c 1"

## Logging in  https://tunnelbroker.net

curl -s -A "$_ua" -o "$_null" "$_url" --data-urlencode f_user="$_login" --data-urlencode f_pass="$_pass" --data-urlencode redir= --data-urlencode Login=Login --cookie-jar "$_cookie"

# Getting content 
curl -L -s -A "$_ua" --cookie "$_cookie" -o "$_output" "$_url_1" 

if grep  -E "([0-9]{1,3}[\\.]){3}[0-9]{1,3}" "$_output" > /dev/null 2>&1
  then
    __green "Login successful"
## Cleanup 
    sed -i -n '/name="tserv"/p' "$_output"     
    echo 
  else
    __red "Login failed"
    echo 
  exit 2
fi

## IP List
_iplist=$(grep -E -o "([0-9]{1,3}[\\.]){3}[0-9]{1,3}" "$_output" | uniq)

_fastip=$(for X in $_iplist ; do $_ping "$X" ; done | $_grep |awk '{print $4,$7}' | tr -d "time=" |sort -k2n,2 | head -1)

rm -r "$_cookie" 
rm -r "$_output"

__green "Fastest IP = $_fastip ms"
echo 
exit 0

