#!/bin/bash

PROGNAME="${BASH_SOURCE[0]}"
HERE="$(cd "$(dirname "$PROGNAME")" &>/dev/null && pwd)"
READIES=$(cd $HERE/.. && pwd)
. $READIES/shibumi/defs

if [[ $($READIES/bin/isec2) == yes ]]; then
	curl http://169.254.169.254/latest/meta-data/public-ipv4
	exit 0
fi

# is GCP?
gcp_ip=$(curl -s -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip || echo ERROR)
if [[ $gcp_ip != ERROR ]]; then
	echo $gcp_ip
	exit 0
fi

if is_command jq; then
	# is Azure?
	az_ip=$(curl -s -H Metadata:true http://169.254.169.254/metadata/instance?api-version=2017-04-02 | jq -r .network.interface[].ipv4.ipAddress[].publicIpAddress)
	if [[ -n $az_ip ]]; then
		echo $az_ip
		exit 0
	fi
fi

if [[ "$OSTYPE" == "darwin"* ]]; then
	if=$(route -n get 8.8.8.8 | grep interface | awk '{print $2}')
	ifconfig $if | grep inet | grep netmask| awk '{print $2}'
else
	ip route get 8.8.8.8 | head -1 | awk '{print $7}'
fi
