#include "Keyboard.h"
#include "HID.h"

#if F_CPU == 16000000
#error should be running at 8MHz
#endif

void setup() {
    pinMode(A0, INPUT_PULLUP);
    Keyboard.begin();
    Serial.begin(9600);
    Serial.setTimeout(50);
}

void goto_bootloader() {
    cli();
    UDCON |= (1<<DETACH);
    USBCON |= (1<<USBE);

    TIMSK0 = 0;

    MCUCR |= (1<<IVCE);
    MCUCR |= (1<<IVSEL);
    sei();
    asm("jmp 0x7000");
}
    

void check_blcmd() {
    if (Serial.available()) {
        String in = Serial.readStringUntil("\n");
        if (in.equals("bootloader\n")) {
            goto_bootloader();
        }
    }
}

void loop() {
    while (digitalRead(A0) == HIGH) {
        check_blcmd();
        delay(100);
    }

    Keyboard.press(KEY_F14);
    Keyboard.releaseAll();

    while (digitalRead(A0) != HIGH) {
        check_blcmd();
        delay(100);
    }

    Keyboard.press(KEY_F15);
    Keyboard.releaseAll();

}
