#include <errno.h>
#include <os/ArgumentParser.h>
#include <os/File.h>
#include <pwd.h>
#include <sys/pstat.h>
#include <time.h>

Result<int> luna_main(int argc, char** argv)
{
    os::ArgumentParser parser;
    parser.add_description("Show a list of processes on the system.");
    parser.add_system_program_info("ps"_sv);
    parser.parse(argc, argv);

    os::println("UID         PID   PPID       TIME CMD");

    pid_t last = pstat(-1, nullptr);
    for (pid_t pid = 1; pid <= last; pid++)
    {
        static process ps;
        if (pstat(pid, &ps) < 0)
        {
            if (errno == ESRCH) continue;
            return err(errno);
        }

        struct tm tm;
        gmtime_r(&ps.ps_time.tv_sec, &tm);

        char timebuf[256];
        strftime(timebuf, sizeof(timebuf), "%H:%M:%S", &tm);

        const char* user = "???";

        passwd* pw = getpwuid(ps.ps_uid);
        if (pw) user = pw->pw_name;

        os::println("%-8s %6d %6d %10s %s", user, ps.ps_pid, ps.ps_ppid, timebuf, ps.ps_name);
    }

    endpwent();

    return 0;
}