#include <stdint.h>
#include <ulib.h>

uint64_t PID;
Dev_t ps2kbdev;
Dev_t termdev;

void tb_runinitscript(void) {
  dev_gethandle(&termdev, "termdev");

  char *tbargs[] = { "-m", "runfile", "-f", "base:/scripts/init.tb" };
  int32_t tb = proc_spawn("base:/bin/tb", tbargs, ARRLEN(tbargs));
  
  proc_run(tb);

  while(proc_pollstate(tb) != 4) {
    int32_t r;

    char buf[100];
    string_memset(buf, 0, sizeof(buf));
    r = ipc_piperead(tb, 0, (uint8_t *const)buf, sizeof(buf)-1);
    if (r > 0) {
      dev_cmd(&termdev, DEV_TERMDEV_PUTCH, buf, string_len(buf));
    } else {
      schedrelease();
    }
  }
}

void main(void) {
  PID = proc_getpid();
  dev_gethandle(&ps2kbdev, "ps2kbdev");
  dev_cmd(&ps2kbdev, DEV_PS2KBDEV_ATTCHCONS, NULL, 0);

  tb_runinitscript();

  uprintf("Shell exited! Please reboot the system.\n");

  for(;;);
}
