#!/bin/sh

DEPTH=${1:?"FIFO depth is missing"}
BASE=${2:?"Pass DW APB SSI registers address"}
CTRLR0=$((BASE))
CTRLR1=$((BASE + 0x04))
SSIENR=$((BASE + 0x08))
SER=$((BASE + 0x10))
BAUDR=$((BASE + 0x14))
TXFTLR=$((BASE + 0x18))
RXFTLR=$((BASE + 0x1c))
TXFLR=$((BASE + 0x20))
RXFLR=$((BASE + 0x24))
SR=$((BASE + 0x28))
IMR=$((BASE + 0x2c))
ISR=$((BASE + 0x30))
RISR=$((BASE + 0x34))
ICR=$((BASE + 0x48))
DR=$((BASE + 0x60))

# Make sure devmem is found in the system
which devmem 2>1 >/dev/null
[ $? -ne 0 ] && printf "No devmem found\n" && exit 1

# Disable the controller
devmem $SSIENR 32 0x0
# Setup a default mode: TMOD=0x0, FRF=0x0, DFS=0x7
devmem $CTRLR0 32 0x7
devmem $CTRLR1 32 0x0
# Disable all chip-selects
devmem $SER 32 0x0
# Set the maximum baud-rate just to activate the xfer
devmem $BAUDR 32 0x2
# Mask all interrupts to prevent the driver from being bothered
devmem $IMR 32 0xff
# Clear interrupts if any is pending
devmem $ICR 32 > /dev/null

# Print the controller state before doing anything
printf "1. Tx FIFO lvl %u, Rx FIFO lvl %u, RISR 0x%08x\n" \
	"$(devmem $TXFLR 32)" "$(devmem $RXFLR 32)" "$(devmem $RISR 32)"

# Enable the controller and fill the Tx FIFO in with 0xFFs
devmem $SSIENR 32 0x1
IDX=0; while [ $IDX -lt $DEPTH ]; do
	devmem $DR 32 0xff
	IDX=$((IDX + 1))
done

# Print the controller state after it
printf "1. Tx FIFO lvl %u, Rx FIFO lvl %u, RISR 0x%08x\n" \
	"$(devmem $TXFLR 32)" "$(devmem $RXFLR 32)" "$(devmem $RISR 32)"

# Enable communications by activating the very first CS
devmem $SER 32 0x1

# Let the data being transfered and print the state after it
sleep 1
printf "2. Tx FIFO lvl %u, Rx FIFO lvl %u, RISR 0x%08x\n" \
	"$(devmem $TXFLR 32)" "$(devmem $RXFLR 32)" "$(devmem $RISR 32)"
