#!/bin/sh
#set -x
PATH=/bin:/usr/bin:/sbin:/usr/sbin

# Silently exit if the kernel does not support modules or needs modutils.
[ -f /proc/modules ] || exit 0
[ ! -f /proc/ksyms ] || exit 0
[ -x /sbin/modprobe  ] || exit 0

KVER=$(uname -r)
KMAJ=${KVER%${KVER#*.*[^.]}}
KMAJ=${KMAJ%.}

#adding a check to load EXAR module only for Vespa Platform..
PLATFORM=$(cat /proc/platform)

if [ ! -e /var/modules.dep ] ; then
  if [ -w /lib/modules/$KVER/ ]; then
    if [ -x /sbin/depmod  ]
      then
      echo -n "Calculating module dependencies... "
      depmod -n > /var/modules.dep
      ln -sf /var/modules.dep /lib/modules/$KVER/modules.dep
      echo "done."
    fi
  else
    echo "Not running depmod because /lib/modules/$KVER/ is not writeable."
  fi
fi


MODULES_FILE=/etc/modules


revid_0=$(/usr/local/bin/gpiotool --get-data 3 12 | grep -c "Pin is High")
revid_1=$(/usr/local/bin/gpiotool --get-data 3 13 | grep -c "Pin is High")
revid_2=$(/usr/local/bin/gpiotool --get-data 3 14 | grep -c "Pin is High")
revid_3=$(/usr/local/bin/gpiotool --get-data 3 15 | grep -c "Pin is High")
brdrev=$( expr $revid_3 \* 8 + $revid_2 \* 4 + $revid_1 \* 2 + $revid_0)
razorl_rev_p2i=3


# Loop over every line in /etc/modules.
echo 'Loading modules...'
grep '^[^#]' $MODULES_FILE | \
while read module args; do
  [ "$module" ] || continue
  echo "Loading Module $module ..."

if [ "$module" == "enet_switch"  -o "$module" == "mdcio" ]; then
	if [ "$PLATFORM" == "RazorL" ] && [ "$brdrev" -lt "$razorl_rev_p2i" ] ; then
		 # Not used for these platforms
		 continue
	fi
elif [ "$module" == "exaruart" ]; then
	if ! [ "$PLATFORM" == "RazorL" ]; then
		  # Only used on these platforms
		  continue
	fi
elif [ "$module" == "expander_uart" ]; then
	if ! [ "$PLATFORM" == "RazorM" ]; then
		  # Only used on these platforms
		  continue
	fi
elif [ "$module" == "supportfpga" ]; then
	if ! [ "$PLATFORM" == "RazorM" -o \
           "$PLATFORM" == "RazorL" ]; then
		  # Only used on these platforms
		  continue
	fi
fi

modprobe $module $args || true

#  insmod $module $args || true
done
echo "All modules loaded."

# Just in case a sysadmin prefers generic symbolic links in
# /lib/modules/boot for boot time modules we will load these modules.
#boot="$(modprobe --list --type boot)"
#for d in $boot; do
#    mod="${d##*/}"
#    mod="${mod%.ko}"
#    modprobe "$mod"
#done

if [ -r /etc/modprobe.conf ] \
	&& ! grep -q '^include.*modprobe.d' /etc/modprobe.conf; then
   echo 'WARNING: /etc/modprobe.conf exists but does not include /etc/modprobe.d/!'
fi

exit 0

