#!/bin/bash

(
PORT=9991


CODE=$1
if [ $CODE == 'wrkey' ]
then
  CODE=$2
fi
RETRIES=5


for ((i=0; i<20; i++)) 
do
	if echo -e "serial\\nquit" | nc -i 1 localhost $PORT | tee /tmp/spresult && 
           	cat /tmp/spresult | grep -q "300 SERIAL" 
	then 
		break 
	fi 
done 

for ((i=0; i<$RETRIES; i++))
do
  
  echo -e "serial\\nupdate $CODE\\nquit" | nc -i 1 localhost $PORT | tee /tmp/spresult
 
  cat /tmp/spresult | grep -q "200 O\\.K\\." && break
done
rm /tmp/spresult

if [ $i -eq $RETRIES ]
then
  echo some error occured
  exit 1
fi
echo spinkey updated OK
) 2>/dev/null
exit

