#!/usr/bin/env bash
#===============================================================================
#
# DIRECTORY:
#   ---
#
# FILE:
#   ./network_plugin.sh
#
# USAGE:
#     . network_plugin.sh
#   OR
#     source network_plugin.sh
#
# DESCRIPTION:
#   Network plugin (library) to generate content with simple template engine.
#
# BUGS:
#   ---
#
# TESTS:
#   - shellcheck -s bash -e SC2034,SC2016 ./hardware_plugin.sh
#   - shellcheck -s ksh -e SC2034,SC2016 ./hardware_plugin.sh
#   - shellcheck -s dash -e SC2034,SC2016 ./hardware_plugin.sh
#
# AUTHOR:
#   Patrick Neumann, patrick@neumannsland.de
#
# COAUTHOR(S):
#   Odin Heitmann, odin.heitmann@gmail.com
#
# COMPANY:
#   (privately)
#
# VERSION:
#   1.1
#
# LINK TO THE MOST CURRENT VERSION:
#   (Sorry, we bet, I'm not allowed to publish it over GitHub!)
#
# CREATED:
#   2018-06-05
#
# COPYRIGHT (C):
#   2018 - Patrick Neumann & Odin Heitmann
#
# LICENSE:
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
# WARRANTY:
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# NOTES:
#   ---
#
# TODO:
#   ---
#
# HISTORY:
#   1.0 - P. N. & O. H. - Initial (for the trainers eyes only) release
#   1.1 - P. N. - added network plugin
#
#===============================================================================

#-------------------------------------------------------------------------------
# Check if functions library is loaded first.
#-------------------------------------------------------------------------------
if [ "${FUNCTIONS_LOADED}" != "true" ] ; then
  printf "\\n\\033[01;31;40mERROR: functions library not loaded... EXIT!!!\\033[00m\\n\\n"
  exit 200
fi

#-------------------------------------------------------------------------------
# Check if temblate engine library is loaded first.
#-------------------------------------------------------------------------------
if [ "${TEMPLATE_ENGINE_LOADED}" != "true" ] ; then
  error_exit "template_engine.sh not loaded" 200
fi

#=== CONFIGURATION (static) ====================================================
#assign_binary "xyz"                                         # (un)common

#=== FUNCTION ==================================================================
# NAME: get_hardware_info
# DESCRIPTION: "Grep" information and store into vars.
# PARAMETERS: none (global vars will be used.)
#===============================================================================
get_network_info () {
  # NOT in iTunes Backup!
  readonly NETWORK_INTERFACES_PLIST="$( ${BIN_FIND} "${IOS_BACKUP}" -type f -name "NetworkInterfaces.plist" )"

  if [ -z "${NETWORK_INTERFACES_PLIST}" ] ; then
    readonly NETWORK_INTERFACES_SOURCE="<code>NetworkInterfaces.plist not found</code>"
    error "NetworkInterfaces.plist not found"
    readonly MAC_ADDRESS="unknown"
	else
    readonly NETWORK_INTERFACES_SOURCE="<a href='NetworkInterfaces.plist' target='_blank'><code>${NETWORK_INTERFACES_PLIST/${IOS_BACKUP}/\/private\/var}</code></a>"
    plist_bin2xml "${NETWORK_INTERFACES_PLIST}" "${FOLDER}/NetworkInterfaces.plist"

    readonly MAC_ADDRESS="$( ${BIN_GREP} --fixed-strings --after-context=3 "IOMACAddress" "${FOLDER}/NetworkInterfaces.plist" \
	                         | ${BIN_GREP} --invert-match "<" \
                           | ${BIN_HEAD} -n 1 \
                           | ${BIN_TR} -d [[:space:]] \
	                         | ${BIN_BASE64} --decode \
	                         | ${BIN_XXD} -plain \
	                         | ${BIN_SED} 's/\(..\)/\1:/g;s/:$//' )"
  fi

  #--- next source ---

  # NOT in iTunes Backup!
  # db/dhcpclient/leases/en0-1,c0:f2:fb:b8:8a:63
  readonly DHCPC_LEASES_PLIST="$( ${BIN_FIND} "${IOS_BACKUP}" -type f -name "en0-1,${MAC_ADDRESS}" )"

  if [ -z "${DHCPC_LEASES_PLIST}" ] ; then
    readonly DHCPC_LEASES_SOURCE="<code>en0-1,${MAC_ADDRESS} not found</code>"
    error "en0-1,${MAC_ADDRESS} not found"
  else
    readonly DHCPC_LEASES_SOURCE="<a href='en0-1,${MAC_ADDRESS}' target='_blank'><code>${DHCPC_LEASES_PLIST/${IOS_BACKUP}/\/private\/var}</code></a>"
    plist_bin2xml "${DHCPC_LEASES_PLIST}" "${FOLDER}/en0-1,${MAC_ADDRESS}"

	  readonly CLIENT_IP="$( ${BIN_GREP} --fixed-strings --after-context=1 "<key>IPAddress</key>" "${FOLDER}/en0-1,${MAC_ADDRESS}" \
		                       | ${BIN_TAIL} -n 1 \
		                       | ${BIN_SED} "${SED_EXT_REGEXP}" 's|[[:space:]]*</?string>||g' )"

    readonly LEASE_START_DATE="$( ${BIN_GREP} --fixed-strings --after-context=1 "LeaseStartDate" "${FOLDER}/en0-1,${MAC_ADDRESS}" \
		                              | ${BIN_TAIL} -n 1 \
		                              | ${BIN_SED} "${SED_EXT_REGEXP}" 's|[[:space:]]*</?string>||g' )"

    readonly BSSID="$( ${BIN_GREP} --fixed-strings --after-context=3 "RouterHardwareAddress" "${FOLDER}/en0-1,${MAC_ADDRESS}" \
	                     | ${BIN_GREP} --invert-match "<" \
                       | ${BIN_HEAD} -n 1 \
                       | ${BIN_TR} -d [[:space:]] \
	                     | ${BIN_BASE64} --decode \
	                     | ${BIN_XXD} -plain \
	                     | ${BIN_SED} 's/\(..\)/\1:/g;s/:$//' )"

	  readonly ROUTER_IP="$( ${BIN_GREP} --fixed-strings --after-context=1 "<key>RouterIPAddress</key>" "${FOLDER}/en0-1,${MAC_ADDRESS}" \
		                       | ${BIN_TAIL} -n 1 \
		                       | ${BIN_SED} "${SED_EXT_REGEXP}" 's|[[:space:]]*</?string>||g' )"

	  readonly ESSID="$( ${BIN_GREP} --fixed-strings --after-context=1 "SSID" "${FOLDER}/en0-1,${MAC_ADDRESS}" \
		                   | ${BIN_TAIL} -n 1 \
		                   | ${BIN_SED} "${SED_EXT_REGEXP}" 's|[[:space:]]*</?string>||g' )"
  fi

	if [ "${DEBUG}" = "on" ] ; then
	  ${BIN_PRINTF} "MAC_ADDRESS: %s\\n" "${MAC_ADDRESS}" 1>&2
	  ${BIN_PRINTF} "CLIENT_IP: %s\\n" "${CLIENT_IP}" 1>&2
	  ${BIN_PRINTF} "LEASE_START_DATE: %s\\n" "${LEASE_START_DATE}" 1>&2
	  ${BIN_PRINTF} "BSSID: %s\\n" "${BSSID}" 1>&2
	  ${BIN_PRINTF} "ROUTER_IP: %s\\n" "${ROUTER_IP}" 1>&2
	  ${BIN_PRINTF} "ESSID: %s\\n" "${ESSID}" 1>&2
	fi
}

#-------------------------------------------------------------------------------
# Partial template for network information for the simple template engine.
#-------------------------------------------------------------------------------
NETWORK_INFORMATION=$( ${BIN_CAT} <<'EOF'
          <h2>Network</h2>
          <h4>Sources</h4>
          <ul class="file">
            <li>${NETWORK_INTERFACES_SOURCE}</li>
            <li>${DHCPC_LEASES_SOURCE}</li>
          </ul>
          <h3>Information</h3>
          <table>
            <tr>
              <td>MAC Address (Wi-Fi):</td>
              <td>${MAC_ADDRESS}</td>
            </tr>
            <tr>
              <td>Client IP Address:</td>
              <td>${CLIENT_IP}</td>
            </tr>
            <tr>
              <td>Lease start date:</td>
              <td>${LEASE_START_DATE}</td>
            </tr>
            <tr>
              <td>BSSID:</td>
              <td>${BSSID}</td>
            </tr>
            <tr>
              <td>Router IP Address:</td>
              <td>${ROUTER_IP}</td>
            </tr>
            <tr>
              <td>(E)SSID:</td>
              <td>${ESSID}</td>
            </tr>
          </table>
EOF
)

readonly NETWORK_PLUGIN_LOADED="true"

if [ "${DEBUG}" = "on" ] ; then
  ${BIN_PRINTF} "INFO: network_plugin.sh loaded.\\n" 1>&2
fi
# Do not use "exit" at the end of a sourced library!