#!/bin/bash

. /tmp/cmdline 
. /usr/bin/i2csetup

type=$1
subtype=$2
revision=$3
serial=$4
hwserial=$5

if [ -z "$(which i2cutil)" ] ; then
    "i2cutil not found"
    exit 1
else
    
    while [ -z "${type}" ]; do
        read -p "Unit type (1/2)? " type
        if [ "${type}" != "1" -a "${type}" != "2" ]; then
            echo "wrong type"
            type=''
        fi
    done
    while [ -z "${subtype}" ]; do
        read -p "Channel type (0/1)"?  subtype
        if [ "${subtype}" != "1" -a "${subtype}" != "2" ]; then
            echo "wrong subtype"
            subtype=''
        fi
    done
    while [ -z "${revision}" ]; do
        read -p "Board revision (a2/a3)? " revision
        if [ "${revision}" != "a2" -a "${revision}" != "a3" ]; then
            echo "wrong revision"
            revision=''
        fi
    done
    while [ -z "${serial}" ]; do
        read -p "Serial number? " serial
   #if [ ! ${serial} -eq ${serial} 2> /dev/null ]; then
        if [  ${serial} -eq ${serial} 2> /dev/null ]; then
            i=0 # just syntactical reasons   
        else 
            echo "Not a number"
            serial=''
        fi
    done

    while [ -z "${hwserial}" ]; do
        read -p "HW Serial number? " serial
   #if [ ! ${hwserial} -eq ${hwserial} 2> /dev/null ]; then 
        if [  ${hwserial} -eq ${hwserial} 2> /dev/null ]; then
            i=0 # just syntactical reasons   
        else 
            echo "Not a number"
            hwserial=''
        fi
    done
    
    w1=$(printf "0x0000%02x%02x" ${type} ${subtype})
    w2=$(printf "0x000000%s" ${revision})
    w3=$(printf "0x%08x" $serial)
    w4=$(printf "0x%08x" $hwserial)
    
    i2cutil -y ${I2CCONFIGBUS} ${I2CCONFIGADDRESS} 0 ${w1} bl > /dev/null
    i2cutil -y ${I2CCONFIGBUS} ${I2CCONFIGADDRESS} 4 ${w2} bl > /dev/null
    i2cutil -y ${I2CCONFIGBUS} ${I2CCONFIGADDRESS} 8 ${w3} bl > /dev/null
    i2cutil -y ${I2CCONFIGBUS} ${I2CCONFIGADDRESS} 12 ${w4} bl > /dev/null
    
    W1=$(printf "0x%08x 0x%08x 0x%08x 0x%08x\n" $(i2cutil -y -r ${I2CCONFIGBUS} ${I2CCONFIGADDRESS} 0 bl) $(i2cutil -y -r ${I2CCONFIGBUS} ${I2CCONFIGADDRESS} 4 bl) $(i2cutil -y -r ${I2CCONFIGBUS} ${I2CCONFIGADDRESS} 8 bl) $(i2cutil -y -r ${I2CCONFIGBUS} ${I2CCONFIGADDRESS} 12 bl))
    
    #echo "${W1}"
    exit
fi
