#!/bin/bash
#
#   Version 1.1
#
#   Copyright 2016-2018 Lee Djavaherian
#
#   This file is part of TrillSat.
#
#   TrillSat is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   TrillSat is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with TrillSat.  If not, see <http://www.gnu.org/licenses/>.
###################################################################################

cd /trillsat
if [ `gpio -g read 5` -eq 0 ]; then
   echo "MISO line to Sawyer is sinking.  First, I will turn on LED on Huckleberry to try and free up. Press Enter to continue."
   read x
   i2ctransfer -y 1 w2@0x52 0xB7 0x01
   sleep 1
   i2ctransfer -y 1 r1@0x52
   echo "If result is 0xff, command is success."
fi

if [ `gpio -g read 5` -eq 0 ]; then
   echo "Hall on gpio 5 is still sinking, can not program until motor moved away from hall or overcurrent can burn out Pi gpio 5."
else
   echo "Compiling..."
   cat trillsat.c | sed 's/CHIP-NAME-INSERTED-FROM-SCRIPT/SAWYER/' > sawyer.c
   avr-gcc -mmcu=attiny1634 -Os sawyer.c -o sawyer.o
   sudo avr-objcopy -j .text -j .data -O ihex sawyer.o sawyer.hex
   echo "Burn Sawyer Flash.  Press Enter to start burn."
   read x
   sudo avrdude -pt1634 -c linuxgpio -U flash:w:sawyer.hex:i -C /trillsat/trillsat_saw_avrdude.conf
   gpio -g mode 2 alt0
   gpio -g mode 3 alt0
   sudo i2cdetect -y 1
fi
