#!/bin/bash

#Run as root
[ `whoami` != root ] && echo Error: Run this script\($0\) as a root user && exit 1

# Make sure this is Jetson_TX1
if [ "$(cat /proc/cpuinfo | grep -i jetson_tx1)" = "" ]; then
	echo "This utility is for Jetson-TX1 only."
	echo "Usage on any other platform can cause system damage. Exiting."
	exit 1
fi

if [ ! -e /lib/firmware/brcm ] ; then
echo "Wifi Firmware not found. Please ensure you have installed the NVIDIA linux driver binaries"
exit 1
fi
### Create the output file
out_file=/home/ubuntu/wifi-config-check-log
if [ -e $out_file ] ; then
  mv $out_file $out_file.old
fi
touch $out_file
echo "## This generated file provides details if the Jetson-TX1 is configured properly for Wireless connections or not" >> $out_file

self=$(basename $0)
## Check for i2cdump and enable source list ONLY if i2cdump is not installed already
i2cdump_avail=`which i2cdump`
i2cget_avail=`which i2cget`
i2cset_avail=`which i2cset`
if [[ "$i2cdump_avail" = "" || "$i2cget_avail" = "" || "$i2cset_avail" = "" ]] ; then
	echo "The i2c-tools package is required."
	read -p "Download i2c-tools via apt-get? [Y/n]:" get_tools
	case $get_tools in
		[nN]* ) echo "Tools download declined. Unable to continue." && exit 1;;
		*     ) ;;
	esac
	self=$(basename $0)
	cat /etc/apt/sources.list | sed 's/^# deb /deb /g' > /home/ubuntu/tmp-$self.txt
	cp /home/ubuntu/tmp-$self.txt /etc/apt/sources.list
	rm /home/ubuntu/tmp-$self.txt
	echo "Running apt-get update..."
	apt-get update > /dev/null 2>&1
	echo "Running apt-get install i2c-tools"
	apt-get install i2c-tools > /dev/null 2>&1
	if [ $? != 0 ]; then
		echo "apt-get install i2c-tools failed. Please check network connections."
		exit 1
	fi
fi

i2cdump_avail=`which i2cdump`

if [ "$i2cdump_avail" != "" ] ; then 
  ### Now try to get the serial number information of Module and Base board
  cvm_addr=0x50
  cvb_addr=0x57
  for I in $cvm_addr $cvb_addr ; do
    if [ "$I" = "$cvm_addr" ] ; then
      phrase=`echo "Serial Number of Module"`
    else
      phrase=`echo "Serial Number for Base board"`
    fi
  #  echo $phrase
    # First get the CVM serial number
    mapfile -t sn_lines < <( i2cdump -f -y -r 74-86 2 $I b )

    len=${#sn_lines[@]}
    if [ "$len" -ne "3" ]; then
            echo "FAILED to get $phrase!!" >> $out_file
            echo "EEPROM content:" >> $out_file
            i2cdump -f -y 2 $I b >> $out_file
    else 
    sn_str1=$(echo ${sn_lines[1]} | rev | cut -d' ' -f1 | rev)
    sn_str2=$(echo ${sn_lines[2]} | rev | cut -d' ' -f1 | rev)
    sn_str=$sn_str1$sn_str2
    echo "$phrase is $sn_str" >> $out_file
    fi
  done
fi

function add_to_crc8()
{
	local b=$1
	local crc=$2
	local __returnvar=$3
	local b2=$b
	local i=0
	if [[ "$b" -le "0" ]]; then
		b2=$(($b + 256))
	fi
	for ((i=0; i<8; i++)); do
		temp1=$(($b2 ^ $crc))
		temp2=$(($temp1 & 1))
		crc=$(($crc >> 1))
		b2=$(($b2 >> 1))
		if [[ "$temp2" -eq "1" ]]; then
			crc=$(($crc ^ 140))
		fi
	done
	eval $__returnvar=$crc
}

function calc_eeprom_crc8()
{
	local __returnvar=$1
	local fix_byte154=$2
	local crc=0
	local i=0
	for ((i=0; i<255; i++)); do
		local byte=$(i2cget -f -y 2 0x50 $i b)
		[ $? -ne 0 ] && echo "i2cget failed on byte $i! aborting." && exit 1
		# Replace byte 154 with the correct value if necessary
		[[ "$i" == "154" ]] && [ "$fix_byte154" == "true" ] && byte=0x1c
		add_to_crc8 $byte $crc curr_crc
		crc=$curr_crc
	done
	eval $__returnvar=$crc
}

function fix_net_naming()
{
	# If the wifi interface had been enabled with default MAC address,
	# then there would be a persistent net naming rule for it. In that
	# case remove the rule to avoid naming problems.
	# We only handle the default case where the rules are in
	# /etc/udev/rules/70-persistent-net.rules.
	echo "Fixing naming of wlan interface."
	local rules_file="/etc/udev/rules.d/70-persistent-net.rules"
	local tmp_rules="/home/ubuntu/tmp-$self.rules"
	cat $rules_file | sed 's/^SUBSYSTEM.*00:90:4c.*wlan/# &/g' > $tmp_rules
	cp $tmp_rules $rules_file
	rm $tmp_rules
}

function check_patch_eeprom()
{
	# Check byte 154 to see if EEPROM needs patching.
	echo "Checking MAC address configuration" 
	if [ -f /proc/device-tree/chosen/nvidia,wifi-mac ]; then
		echo "MAC address configuration is correct."
		return
	fi
	byte154=$(i2cget -f -y 2 0x50 154 b)
	[ $? -ne 0 ] && echo "Failed to check MAC address configuration!" && return 1
	if [[ "$byte154" -ne "0x1c" ]]; then
		echo "Configuration error found. Correcting..."
		echo "Please do not interrupt, or system data corruption can occur."
		# First re-calculate CRC with the corrected value.
		# Only write to the EEPROM as the very last step.
		calc_eeprom_crc8 crc8 true

		# Write both the corrected value and the new CRC
		# Write CRC first because if somehow byte 154 doesn't get updated,
		# it's possible to rerun the test.
		i2cset -f -y 2 0x50 255 $crc8
		[ $? -ne 0 ] && echo "Failed to update CRC!" && return 1
		i2cset -f -y 2 0x50 154 0x1c
		[ $? -ne 0 ] && echo "Failed to correct error!" && return 1

		fix_net_naming

		echo "Error corrected. The correct MAC addresses will be effective after reboot."
	else
		echo "No error found. Nothing to be done."
	fi
	return 0
}

echo ""
check_patch_eeprom
eeprom_status=$?
echo "Checking WiFi settings next"

echo $border | tee -a $out_file

# Now parse dmesg to find if wifi settings has been performed
echo "========================================="
dmesg > /home/ubuntu/dmsg
if grep "Firmware version = wl0" /home/ubuntu/dmsg > /dev/null
then
	if [ $eeprom_status -eq 0 ]; then
		echo "Your developer kit is functioning correctly." | tee -a $out_file
	else
		echo "An error occurred while updating firmware contents. Please re-run this test. If you encounter this error again, visit the product support page at https://developer.nvidia.com/embedded/support" | tee -a $out_file
	fi
else
	failure_msg="dhd_bcmsdh_send_buf: sdio error -1, abort command and terminate frame."
	if grep "$failure_msg" /home/ubuntu/dmsg > /dev/null
	then
		echo "A manufacturing problem has been detected. This may impact performance and stability of your developer kit. Please go to https://developer.nvidia.com/embedded/support to request a replacement. We are sorry for the inconvenience." | tee -a $out_file
	else
		echo "Test inconclusive (WiFi settings unknown). Please make sure WiFi is enabled under network settings, reboot the system and re-run this test. If you encounter this error again, visit the product support page at https://developer.nvidia.com/embedded/support" | tee -a $out_file
	fi
fi

rm -rf /home/ubuntu/tmp.txt /home/ubuntu/dmsg
echo "========================================="
echo "Please check file: $out_file for more details"
echo "========================================="

exit 1

