#! /bin/bash
# Detect attached pyboard variant build and deploy
# Assumes only one device attached and that this will appear as /dev/pyboard (udev rule)
# requires pyb_check
# Also requires the pyboard.py utility to be on the path (micropython/tools/pyboard.py)

MPDEVICE='/dev/pyboard'
MANIFESTS='/mnt/qnap2/Scripts/manifests'
# Determine board type
BOARD=$(pyb_check $MPDEVICE)
# Currently have only two manifest variants for V1.x and D
if [[ $BOARD == 'PYBV11' || $BOARD == 'PYBV10' || $BOARD == 'PYBLITEV10' ]]
then
    MANIFEST=$MANIFESTS/pyb_v1_manifest.py
fi
if [[ $BOARD == 'PYBD_SF2' || $BOARD == 'PYBD_SF3' || $BOARD == 'PYBD_SF6' ]]
then
    MANIFEST=$MANIFESTS/pyb_d_manifest.py
fi

# Check for user override of frozen directory
if [ $FROZEN_DIR ]
then
    echo Frozen modules located in $FROZEN_DIR
else
    FROZEN_DIR='modules'
fi

if [ $BOARD ]
then
    echo Building for $BOARD
    cd $MPDIR/ports/stm32
    if [ $# -eq 1 ] && [ $1 = "--clean" ]
    then
        make BOARD=$BOARD clean
    fi
    if make -j 8 BOARD=$BOARD FROZEN_MANIFEST=$MANIFEST && pyb_boot $MPDEVICE
    then
        sleep 1
        make PYTHON=python3 BOARD=$BOARD FROZEN_MANIFEST=$MANIFEST deploy
    else
        echo Build failure
    fi
    cd -
else
    echo Incorrect board type
fi

