pub mod drivers;
pub mod init;

use crate::print;
use crate::println;
use core::arch::asm;

#[naked]
#[no_mangle]
unsafe extern "C" fn _boot() -> ! {
    #[rustfmt::skip]
    asm!("
        csrw sie, zero
        csrci sstatus, 2

        .option push
        .option norelax
        lla gp, __global_pointer$
        .option pop

        lla sp, __tmp_stack_top

        lla t0, __bss_start
        lla t1, __bss_end

        1:
            beq t0, t1, 2f
            sd zero, (t0)
            addi t0, t0, 8
            j 1b

        2:
            j {}
    ",
    sym _start, options(noreturn));
}

extern "C" fn _start() -> ! {
    use crate::serial_println;

    let uart = crate::arch::drivers::uart::Uart::new(0x1000_0000);
    uart.init();
    log!("Hello, world!\r");

    loop {
        if let Some(c) = uart.get() {
            match c {
                66 => break,
                10 | 13 => {
                    uart.put('\n' as u8);
                    uart.put('\r' as u8);
                }

                /*
                                91 => {
                                    if let Some(ch) = uart.get() {
                                        match ch as char {
                                            'A' => {
                                                serial_println!("That's the up arrow!");
                                            }
                                            'B' => {
                                                serial_println!("That's the down arrow!");
                                            }
                                            'C' => {
                                                serial_println!("That's the right arrow!");
                                            }
                                            'D' => {
                                                serial_println!("That's the left arrow!");
                                            }
                                            _ => {
                                                serial_println!("That's something else!");
                                            }
                                        }
                                    }
                                }
                */
                _ => {
                    uart.put(c);
                }
            }
        }
    }

    serial_println!("Serial connection closed.\r");
    sloop()
}

pub fn sloop() -> ! {
    loop {
        unsafe {
            asm!("wfi");
        };
    }
}

pub fn shutdown() {}
pub fn generate_process_pass() -> u128 {
    123
}
