#!/bin/bash
###################################################################### 
#Copyright (C) 2020  Kris Occhipinti
#https://filmsbykris.com

#This program 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.

#This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
###################################################################### 

mk="/usr/share/arduino/Arduino.mk"
sketchdir="$HOME/sketchbook"
[[ ! -f "$mk" ]] && sudo apt-get install arduino-mk

mkdir -p "$sketchdir" &&
cd "$sketchdir" &&
ln -s "$mk" 2> /dev/null
mkdir -p blink &&
cd blink &&

cat << EOF > blink.ino
// Blink

void setup(void) {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, LOW);
  delay(1000);
  digitalWrite(13, HIGH);
  delay(1000);
}
EOF

tag="atmega328    Arduino Duemilanove or Nano w/ ATmega328     
atmega168    Arduino NG or older w/ ATmega168       
atmega8      Arduino NG or older w/ ATmega8       
bt           Arduino BT w/ ATmega168          
bt328        Arduino BT w/ ATmega328          
diecimila    Arduino Diecimila, Duemilanove, or Nano w/ ATmega168 
fio          Arduino Fio            
lilypad      LilyPad Arduino w/ ATmega168       
lilypad328   LilyPad Arduino w/ ATmega328       
mega         Arduino Mega (ATmega1280)          
mega2560     Arduino Mega 2560            
mini         Arduino Mini           
pro          Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega168   
pro328       Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328   
pro5v        Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega168    
pro5v328     Arduino Pro or Pro Mini (5V, 16 MHz) w/ ATmega328    
uno          Arduino Uno"

tag="$(echo "$tag" |fzf --prompt "Select Board"|awk '{print $1}')"

#Set Tag
#echo "What is your TAG? (example: atmega328)"
#read tag
[[ "$tag" = "" ]] && tag="atmega328"
echo "Tag set to $tag"

#Set Port
port="$(ls /dev/ttyUSB*|fzf --prompt "What is your Serial Port (example: ttyUSB0)")"
[[ "$port" = "" ]] && port="ttyUSB0"
echo "Serial Port set to $port"

cat << EOM > Makefile
BOARD_TAG = $tag
ARDUINO_PORT = $port
ARDUINO_LIBS =
ARDUINO_DIR = /usr/share/arduino
include ../Arduino.mk
EOM

echo "Setup complete!!!"
echo "'make' to make"
echo "'make upload' to make and upload to board"
echo "Project is in $HOME/sketchbook"