#!/bin/sh
#
#######################
# serial number check #
#######################
#
# A. Hauff, S. Dahinden, D. Chapman, 19. 10. 2021
#

echo "0_check_serial_number.sh: start verification of serial number"

# get device serial number filter from matching.txt
serialnumber_filter="$(grep -oE 'package_sn,([][\*0-9A-Z-]+),end' ./matching.txt | grep -oE [][\*0-9A-Z-]+)"

# turn serial number filter string into regular expression
serialnumber_regex="${serialnumber_filter//[*]/[0-9A-Z]}"

# get the serial number
serialnumber="$(grep -o -m 1 '[0-9A-Z]\{3\}-[0-9A-Z]\{9\}-[0-9A-Z]\{4\}' /anapico/dev/sn)"

# apply serial number regular expression to the serial number and check if they match
echo "0_check_serial_number.sh: verify serial number ${serialnumber} against filter ${serialnumber_filter}"
serialnumber_match="$(grep -o -m 1 $serialnumber_regex /anapico/dev/sn)"

if [[ $serialnumber_match ]] 
then
    echo "0_check_serial_number.sh: serialnumber ${serialnumber} is compatible --> proceed"
else
    echo "0_check_serial_number.sh: ERROR - incompatible serialnumber: ${serialnumber}, --> stop uploading firmware"
    kill -SIGKILL $PPID
    echo "0_check_serial_number.sh: reboot"
    shutdown -r now 
    exit 1
fi
