#!/bin/bash

set -e

function print_usage {
    echo "Usage: set-device [ DEVICE_NAME | DEVICE_DIR ]"
}

function list_known_devices {
    echo "Known devices:"
    ls -1 devices | while read f; do
        if [[ -d "devices/$f" && -f "devices/$f/device_config.h" && -f "devices/$f/device_main.cpp" ]]; then
            echo "$f"
        fi
    done
}

function link_device_directory {
    if [[ "$1" == /* ]]; then
        DIR="$1"
    else
        DIR="../$1"
    fi
    echo "Linking main/device to $DIR"
    rm "main/device"
    ln -s "$DIR" "main/device"
    touch --no-create "device/device_config.h"
    touch --no-create "device/device_main.cpp"
}

if [[ -z "$1" ]]; then
    print_usage
    list_known_devices
elif [[ -f "$1/device_config.h" && -f "$1/device_main.cpp" ]]; then
    echo "Found device in directory $1"
    link_device_directory "$1"
elif [[ -f "devices/$1/device_config.h" && -f "devices/$1/device_main.cpp" ]]; then
    echo "Found device $1 in devices directory"
    link_device_directory "devices/$1"
else
    echo "Cannot find device_config.h and device_main.cpp in one of the following directories:"
    echo "$1"
    echo "devices/$1"
fi