#!/bin/sh

# Example script called by Mender client to collect device identity data. The
# script needs to be located at
# $(datadir)/mender/identity/mender-device-identity path for the agent to find
# it. 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 identity data in <key>=<value> format, one
# entry per line. Example
#
# $ ./mender-device-identity
# mac=de:ad:ca:fe:00:01
# cpuid=1112233
#
# == Linux ==
# This example script collects the MAC address of a network interface with the
# type ARPHRD_ETHER and it will pick the interface with the lowest ifindex
# number if there are multiple interfaces with that type. The identity data is
# output in the following format:
#
# mac=00:01:02:03:04:05
#
# == QNX ==
# The identity data is in the same format, but the MAC address is the address of
# the first device marked as active in the `ifconfig` output.
#

set -ue

case $(uname -s) in
  Linux)
    SCN=/sys/class/net
    min=65535
    arphrd_ether=1
    ifdev=

    # find iface with lowest ifindex, skip non ARPHRD_ETHER types (lo, sit ...)
    for dev in $SCN/*; do
        if [ ! -f "$dev/type" ]; then
            continue
        fi

        iftype=$(cat $dev/type)
        if [ $iftype -ne $arphrd_ether ]; then
            continue
        fi

        # Skip dummy interfaces
        if echo "$dev" | grep -q "$SCN/dummy" 2>/dev/null; then
    	continue
        fi

        idx=$(cat $dev/ifindex)
        if [ $idx -lt $min ]; then
            min=$idx
            ifdev=$dev
        fi
    done

    if [ -z "$ifdev" ]; then
        echo "no suitable interfaces found" >&2
        exit 1
    else
        echo "using interface $ifdev" >&2
        # grab MAC address
        echo "mac=$(cat $ifdev/address)"
    fi
    ;;

  QNX)
    nics=$(ifconfig | grep -E --only-matching '^[A-Za-z0-9_]+')
    for nic in $nics; do
      if ifconfig $nic | grep -q active; then
        echo "using interface $nic" >&2
        echo "mac=$(ifconfig $nic | sed -rn '/ether/s/\s+ether\s+//p')"
        exit 0
      else
        echo "$nic not active" >&2
      fi
    done
    echo "no suitable interface found" >&2
    exit 1
    ;;
esac
