#!/usr/bin/env bash
#we don't care about interface so wont use /lib/systemd/systemd-networkd-wait-online

source /etc/environment
export $(cat /etc/environment | grep -vE '^$|^#' | cut -d= -f1) #export all variables from file

ubuntu_ver=$(lsb_release -rs | tr -d '.')

if [[ $ubuntu_ver -ge 2004 ]]; then
    [[ $(iw dev | grep "Interface" | awk '{print $2}' | wc -w) -gt 0 ]] && TIMEOUT=45 || TIMEOUT=15
    /lib/systemd/systemd-networkd-wait-online --timeout=$TIMEOUT --any
fi

#[ -t 1 ] &&
. colors #use them anyway

function echo2 {
	echo -e "$1" > /dev/tty1
	echo -e "$1"
}


#Also ping in addition to nslookup
PING_ENABLED=0
#Tries count
COUNT=5
#Verbose
VERBOSE=0


for i in "$@"; do
	case $i in
		--ping)
			PING_ENABLED=1
			shift
		;;
		--count=*)
			COUNT="${i#*=}"
			shift
		;;
		--verbose|-v)
			VERBOSE=1
			shift
		;;
		*)
			# unknown option
			shift
		;;
	esac
done


API_HOST="api.hiveos.farm"
[[ -e $RIG_CONF ]] && . $RIG_CONF
[[ ! -z $HIVE_HOST_URL ]] && API_HOST=`echo $HIVE_HOST_URL | awk -F'://' '{print $2}'`


host=1.1.1.1
#nslookuphost=hiveos.farm
#nslookuphost=$API_HOST #can't use this as it is cached in /etc/hosts
nslookuphost=`echo $API_HOST | awk -F'.' '{print substr($0,index($0,$2))}'` #drop api. from hostname
#wifi_active=`systemctl is-active wpa_supplicant@wlan0.service`

# backend addressed by an IP (local/white-label server): the label-dropping
# derivation above mangles it (192.168.1.5 -> 168.1.5) and nslookup fails on
# every boot adding ~30s delay. Ping the address itself instead of DNS check.
DNS_CHECK=1
api_addr=${API_HOST%%:*}
if [[ $api_addr =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
	nslookuphost=$api_addr
	DNS_CHECK=0
	PING_ENABLED=1
elif [[ $API_HOST =~ ^\[([0-9a-fA-F:]+)\] ]] || [[ $API_HOST == *:*:* && $API_HOST =~ ^[0-9a-fA-F:]+$ ]]; then
	# bracketed [ipv6]:port or plain ipv6
	nslookuphost=${BASH_REMATCH[1]:-$API_HOST}
	DNS_CHECK=0
	PING_ENABLED=1
fi


check_online() {
	interval=$1
	ping_ok=1
	if [[ $PING_ENABLED == 1 ]]; then
		ping_ok=0
		timeout -s9 6 ping -n -c 1 -w 5 $nslookuphost > /dev/null 2>&1
		exitcode=$?
		[[ $VERBOSE == 1 && $exitcode -ne 0 ]] && echo2 "ping $nslookuphost failed"
		[[ $exitcode == 0 ]] && ping_ok=1
		# returns "Network unreachable" and does not wait
		[[ $exitcode -ne 0 ]] && sleep 1 && return 1
	fi

	#ICMP can be blocked in datacenters so we need to use something else

	ns_ok=0
	if [[ $DNS_CHECK == 0 ]]; then
		# IP backend: reachability already proven by ping above
		ns_ok=1
	else
		timeout $interval nslookup $nslookuphost > /dev/null 2>&1
		exitcode=$?
		[[ $VERBOSE == 1 && $exitcode -ne 0 ]] && echo2 "nslookup $nslookuphost failed"
		[[ $exitcode == 0 ]] && ns_ok=1
	fi

	#Ales gut
	[[ $ping_ok == 1 && $ns_ok == 1 ]] && return 0

	return 1
}

# Do you want a timeout ?
for ((i = 0; i <= $COUNT; i++ )) do
	check_online $((i+1)) &&
		echo2 "[  ${GREEN}OK${NOCOLOR}  ] ${GREEN}Network is online${NOCOLOR}" &&
		exit 0

	[[ $i -gt 0 ]] &&
		echo2 "Waiting for online... $i"
done


echo2 "${RED}Network is offline, check your Internet connection${NOCOLOR}"

exit 1