#!/bin/sh
# 
# Script to reset the SPEC7 card via SMBus
# Author <Ton Damen>tond@nikhef.nl
# Date: 9 april 2020
# Relies on the rpm package "i2c-tools"
#

which i2cdetect > /dev/null 2>&1

if test $? -ne 0; then
	echo "Missing i2c-utils"
	exit
fi

if test $(id -u) -ne 0; then
	echo "Need root privilege"
	exit
fi

BUS=$(i2cdetect -l |  awk -e '/SMBus/ { print substr($1,5)  }')
CHIP_ADDR=0x20
CHIP_INPUT_REG=0
CHIP_OUTPUT_REG=1
CHIP_CONF_REG=3

echo "Found SMBUS on bus $BUS"

REG_VAL=$(i2cget -y $BUS $CHIP_ADDR $CHIP_INPUT_REG  2>/dev/null)

if test -z $REG_VAL; then
	echo "I2C on SPEC not present"
	exit
fi

echo "Read value $REG_VAL on address 0 (expect 0xff)"

echo "Issuing reset.."

# set bit0 to output
i2cset -r -y -m 1 $BUS $CHIP_ADDR $CHIP_CONF_REG 0
# set bit0 to 0
i2cset -r -y -m 1 $BUS $CHIP_ADDR $CHIP_OUTPUT_REG 0
# set bit0 to 1
i2cset -r -y -m 1 $BUS $CHIP_ADDR $CHIP_OUTPUT_REG 1

if test $? -eq 0; then
	echo "Success"
else
	echo "Failed"
fi
