#!/bin/sh

# TODO :
# - Add detection of VPN Interface to remove error message

DEBUG() {
 [ "$_DEBUG" = "on" ] &&  $@
}

# Define VPN interface name
VPNIF="vpnaltinea"

if ! [ -x "$(command -v sendEmail)" ]; then
    echo "sendEmail could not be found, I'll install it for you"
    apt install -y sendemail
fi

if ! [ -x "$(command -v jq)" ]; then
    echo "jq could not be found, I'll install it for you"
    apt install -y jq
fi

# Get public IP addresses
EXTIP4=`curl -s https://checkipv4.altinea.fr/getIP.php`
EXTIP6=`curl -s https://checkipv6.altinea.fr/getIP.php`

# Testing if returned IPs are empty and setting
# a dummy value for later comparison
if [ -z "$EXTIP4" ]; then
	EXTIP4='dummy'
fi
if [ -z "$EXTIP6" ]; then
	EXTIP6='dummy'
fi

# Check if found IPv4 address is configured on this server
if [ $(hostname -I |grep -c $EXTIP4) -ne 0 ]; then
	IP4=$EXTIP4
else
	# Let see if we can find an ip address on the configured VPN interface
	DEBUG echo "Couldn't find a public IPv4 address on this host"
	DEBUG echo "Let see if we find a $VPNIF wireguard interface"
	VPNIP4=`ip -j addr show dev $VPNIF | jq -r '.[0].addr_info | map(select(.family == "inet"))[0].local'`
	if [ -z "$VPNIP4" ]; then
		DEBUG echo "Can't find an IPv4 address on $VPNIF interface"
	else
		DEBUG echo "Found VPN IPv4 : $VPNIP4. Using it for monitoring purposes"
		IP4=$VPNIP4
	fi
fi

# Same routine for IPv6
if [ $(hostname -I |grep -c $EXTIP6) -ne 0 ]; then
	IP6=$EXTIP6
else
	DEBUG echo "Couldn't find a public IPv6 address on this host"
        DEBUG echo "Let see if we find an IPv6 on $VPNIF interface"
        VPNIP6=`ip -j addr show dev $VPNIF | jq -r '.[0].addr_info | map(select(.family == "inet6"))[0].local'`
        if [ -z "$VPNIP6" ]; then
                DEBUG echo "Can't find an IPv6 address on $VPNIF interface"
        else
                DEBUG echo "Found VPN IPv6 : $VPNIP6. Using it for monitoring purposes"
                IP6=$VPNIP6
        fi

fi

# Generate first part on the command
COMMAND="sendEmail -f noc@altinea.fr -u Nouvelle demande de monitoring -t support@altinea.fr -m Nouvelle IP à monitorer :\n"`hostname -f`"\n"

# Add IPv4 if found
if [ -z "$IP4" ]; then
	DEBUG echo "Sorry we're unable to find a routable IPv4 address, sorry !"
else
	COMMAND="$COMMAND IPv4 : $IP4\n"
fi

# Add IPv6 if found
if [ -z "$IP6" ]; then
	DEBUG echo "Sorry we're unable to find a routable IPv6 address, sorry !"
else
	COMMAND="$COMMAND IPv6 : $IP6\n"
fi

COMMAND="$COMMAND -o tls=no -o message-charset=UTF-8  -s zpush.altinea.fr"

# And run the request by mail
if [ "$_DRYRUN" = "on" ]; then
	echo $COMMAND
else
	$COMMAND
fi