#!/bin/bash
ROOT_DIR="$(dirname "$0")"
cd $ROOT_DIR

# TODO: add CMD line args
#  - skip makeconfig

# Pull Klipper
git submodule update --init --recursive

# Select Klipper Config
cd dirs/klipper
make menuconfig
CONFIG_FILES=(`ls config`)
let i=0
C=()
for f in ${CONFIG_FILES[@]}; do
    C+=($i $f)
    let i+=1
done
CONFIG_INDEX=$(dialog --backtitle "drwho@hackers.town" --title "Printer Selection" --menu "Select Printer Config" --output-fd 1 40 0 1 ${C[@]})
CONFIG_FILE=${CONFIG_FILES[$CONFIG_INDEX]}

# Select Serial Device
DEVICES=(`ls /dev/serial/by-id/`)
let i=0
C=()
for f in ${DEVICES[@]}; do
    C+=($i $f)
    let i+=1
done
DEVICE_INDEX=$(dialog --backtitle "drwho@hackers.town" --title "USB Device Selection" --menu "Select USB Device" --output-fd 1 40 0 1 ${C[@]})
DEVICE=${DEVICES[$DEVICE_INDEX]}

# Build Klipper
cat ./config/$CONFIG_FILE | sed -e "s/^serial: .\+$/serial: \/dev\/serial\/by-id\/${DEVICE}/" > ./printer.cfg
make -j$(nproc)

# Flash Firmware
make flash FLASH_DEVICE=/dev/serial/by-id/$DEVICE

# Copy over printer config file
cd $ROOT_DIR
cp dirs/klipper/printer.cfg dirs/printer_data/config/printer.cfg

# Apply Edits to Configs

