#!/bin/bash

function read_current_server_ip_and_interface
{
        SERVER_IP=""
        if [ -z "$SERVER_IP" ]; then
                SERVER_IP=`curl -s ipecho.net/plain ; echo`
                if [[ $(echo $SERVER_IP | grep -cE "([0-9]{1,3}[\.]){3}[0-9]{1,3}") -eq 0 ]]; then
                        echo "dig +short myip.opendns.com @resolver1.opendns.com"
                        SERVER_IP=`dig +short myip.opendns.com @resolver1.opendns.com`
                fi
        fi

        echo "SERVER_IP: $SERVER_IP"

        if [ -z "$INTERFACE" ]; then
                        SYSTEM_INTERFACE=`netstat -ie | grep -B1 $SERVER_IP | head -n1 | awk '{print $1}'`
        fi

        echo "SYSTEM_INTERFACE: $SYSTEM_INTERFACE"

        if [[ `echo $SYSTEM_INTERFACE | grep -cE '^eth[0-9]$'` -eq 0 ]]; then
                if [[ `/bin/hostname -i` != "$SERVER_IP" ]]; then
                        SERVER_IP=`/bin/hostname -i`
                        echo "IPs are diff, we use hostname -i IP instead which is: $SERVER_IP"
                        SYSTEM_INTERFACE=`netstat -ie | grep -B1 $SERVER_IP | head -n1 | awk '{print $1}'`
                        echo "SYSTEM_INTERFACE2: $SYSTEM_INTERFACE"
                fi
        fi
}

read_current_server_ip_and_interface

rx=`vnstat -i $SYSTEM_INTERFACE -tr | grep rx | awk -F " " '{ print $2 " " $3 }'`
rx_speed=`echo $rx | awk '{print $1}'`
rx_unit=`echo $rx | awk '{print $2}'`

tx=`vnstat -i $SYSTEM_INTERFACE -tr | grep tx | awk -F " " '{ print $2 " " $3 }'`
tx_speed=`echo $tx | awk '{print $1}'`
tx_unit=`echo $tx | awk '{print $2}'`

/usr/bin/curl --data "rx_speed=$rx_speed&rx_unit=$rx_unit&tx_speed=$tx_speed&tx_unit=$tx_unit&server_ip=$SERVER_IP" https://psc.sh/check_current_load.php
