#!/bin/sh
#
# Example script called by Mender client to collect inventory data for a
# particular device. The script needs to be located in $(datadir)/mender and its
# name shall start with `mender-inventory-` prefix. The script shall exit with
# non-0 status on errors. In this case the agent will discard any output the
# script may have produced.
#
# The script shall output inventory data in <key>=<value> format, one entry per
# line. Entries appearing multiple times will be joined in a list under the same
# key.
#
# $ ./mender-inventory-geo
# country=Poland
# city=Krakow
# latitude=50.05750
# longitude=19.98020
# ipv4=127.0.0.1
#
# The example script collects information on geo localization
# this can be done in one line:
# curl https://ipvigilante.com/`curl -4 ifconfig.io 2>/dev/null` 2>/dev/null | jq -r 'select(.status == "success") | "country=" + .data.country_name, "city="+.data.city_name, "latitude="+.data.latitude, "longitude="+.data.longitude, "ipv4="+.data.ipv4 | @text'
# but in the following we assume busybox version of the utilities.
# see below for the configuration of the attributes names

err() {
 local rc=$1

 shift
 echo "${0}: $*" >&2
 exit $rc
}

# find the ip address
ip=`wget -qO /dev/stdout --header "Content-Type: text/plain;" \
     --header 'Host: ifconfig.io' --header 'User-Agent: curl/7.67.0' \
     --header 'Accept: */*' ifconfig.io | tail -1`

[ -n "${ip}" ] || err 2 "Unable to get the IP address from ifconfig.io"

# get the information, see https://www.ipvigilante.com/api-developer-docs/
geo=`wget -qO /dev/stdout https://ipvigilante.com/csv/${ip} 2>/dev/null`

[ -n "${geo}" ] || err 3 "Unable to get the geolocalization data from ipvigilante.com"

# the names of the attributes holding the localization data can be configured here
ATTR_NAME_IP="geo-ip"
ATTR_NAME_CONTINENT="geo-continent"
ATTR_NAME_COUNTRY="geo-country"
ATTR_NAME_CITY="geo-city"

echo "${geo}" | awk -v ip="${ATTR_NAME_IP}" -v continent="${ATTR_NAME_CONTINENT}" \
    -v country="${ATTR_NAME_COUNTRY}" -v city="${ATTR_NAME_CITY}" -F',' \
    ' length($NF) == 0 { exit(4) }
      { printf("%s=%s\n%s=%s\n%s=%s\n%s=%s\n",ip,$1,continent,$2,country,$3,city,$6) }
    '

