#!/bin/ash

CANSTATE=$(cat /sys/class/net/can0/operstate)

while [ ! "${CANSTATE}" == "up" ]; do
  sleep 2
  echo "Wait for can0 interface"
  CANSTATE=$(cat /sys/class/net/can0/operstate)  
done

echo "Detected can is up"

SEQ=""

while read line; do
  if [ "$line" == "can0  0A0   [1]  01" ] && [ "$SEQ" == "" ]; then
    SEQ=1
    echo "entered step 1"
  else
    if [ "$line" == "can0  09E   [1]  86" ] && [ "$SEQ" == "1" ]; then
      SEQ=2a
      echo "entered step 2a"
    else
      if [ "$line" == "can0  097   [1]  86" ] && [ "$SEQ" == "1" ]; then
        SEQ=2b
        echo "entered step 2b"
      else
        if [ "$line" == "can0  028   [2]  A5 00" ] && [ "$SEQ" == "2a" ]; then
	  echo "admin"
          touch /tmp/md850admin.request
          memictl start synth_engine
        else
          if [ "$line" == "can0  028   [2]  A5 00" ] && [ "$SEQ" == "2b" ]; then
	    echo "production"
            rm /tmp/md850admin.request
            memictl start synth_engine
          else
            echo "failed with $line"
          fi
        fi
        SEQ=""
      fi
    fi
  fi
done < <(candump can0,020~7FF)
