#!/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
# geo-ip=8.8.8.8
# geo-city=Mountain View
# geo-country=US
# geo-timezone=America/Los_Angeles
#
# The example script collects information on geo localization

err() {
 local rc=$1

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

TIMEOUT=10 # Request timeout
TEMPFILE="/tmp/mender/inventory-geo"

# the names of the attributes holding the localization data can be configured here
ATTR_NAME_IP="geo-ip"
ATTR_NAME_CITY="geo-city"
ATTR_NAME_COUNTRY="geo-country"
ATTR_NAME_TIMEZONE="geo-timezone"
# the following two attributes denote latitude (geo-lat) and longitude (geo-lon)
# as returned by the ipinfo.io in the loc field (loc=latitude,longitude)
ATTR_NAME_LAT="geo-lat"
ATTR_NAME_LON="geo-lon"

if [ ! -f "${TEMPFILE}" ]; then
    ipinfo=$(wget --timeout=${TIMEOUT} -q -O /dev/stdout \
                  --header 'Accept: application/json' \
                  https://ipinfo.io)
    if [ $? != 0 ] || [ -z "${ipinfo}" ]; then
        err 2 "Unable to get IP info from ipinfo.io"
    fi

    # Fetch and cache geo location data
    mkdir -p $(dirname "${TEMPFILE}") || \
        err $? "Failed to create temporary storage for geo location data."

    # Convert JSON (Object{string -> string}) to key=value format.
    ipinfo=$(echo "${ipinfo}" | \
                 tr -d "\n" | \
                 sed 's/^\s*{\(.*\)\s*"\s*}\s*$/\1/' | \
                 sed 's/\([^\\]\)",/\1\n/g' | \
                 sed 's/^\s*"//' | \
                 sed 's/\([^\\]\)\s*"\s*:\s*"/\1=/'
          )

    echo "${ipinfo}" | \
        awk -F'=' -v attr_ip="${ATTR_NAME_IP}" \
            -v attr_city="${ATTR_NAME_CITY}" \
            -v attr_lat="${ATTR_NAME_LAT}" \
            -v attr_lon="${ATTR_NAME_LON}" \
            -v attr_country="${ATTR_NAME_COUNTRY}" \
            -v attr_zone="${ATTR_NAME_TIMEZONE}" '
$1 ~ /^ip/       {printf "%s=%s\n", attr_ip, $2};
$1 ~ /^loc/      {split($2,a,","); printf "%s=%s\n%s=%s\n", attr_lat, a[1], attr_lon, a[2]};
$1 ~ /^city/     {printf "%s=%s\n", attr_city, $2};
$1 ~ /^country/  {printf "%s=%s\n", attr_country, $2};
$1 ~ /^timezone/ {printf "%s=%s\n", attr_zone, $2};
' > "${TEMPFILE}"
fi

cat $TEMPFILE
exit $?
