/**
 * @file Prompt.cpp
 * @author apio (cloudapio.eu)
 * @brief Displays the shell prompt.
 *
 * @copyright Copyright (c) 2024, the Luna authors.
 *
 */

#include "Prompt.h"
#include <luna/String.h>
#include <os/File.h>
#include <os/FileSystem.h>
#include <pwd.h>
#include <stdlib.h>
#include <sys/utsname.h>
#include <unistd.h>

struct utsname g_sysinfo;

const char* hostname = "";
const char* username = "";
char prompt_end = '$';

void setup_prompt()
{
    // Set up everything to form a prompt.
    uname(&g_sysinfo);
    hostname = g_sysinfo.nodename;

    if (getuid() == 0) prompt_end = '#';

    struct passwd* pw = getpwuid(getuid());
    if (pw) { username = pw->pw_name; }
    else { username = getenv("USER"); }
    endpwent();
}

Result<void> display_prompt()
{
    auto cwd = TRY(os::FileSystem::working_directory());
    os::print("\x1b[%dm%s\x1b[m@\x1b[36m%s\x1b[m:\x1b[1;34m%s\x1b[m%c ", getuid() == 0 ? 31 : 35, username, hostname,
              cwd.chars(), prompt_end);

    return {};
}