module patch.newterm;

import st;
import x;
import config;
import patches;
import core.stdc.stdio;
import core.stdc.stdlib;
import core.stdc.string;
import core.stdc.errno;
import core.sys.posix.unistd;
import core.sys.posix.sys.wait;
import std.string : toStringz;

static if (isPatchEnabled!"NEWTERM_PATCH") {
    extern(C) void newterm(const(Arg)* a) {
        int res;
        pid_t child1 = fork();
        switch (child1) {
        case -1:
            die("fork failed: %s\n".toStringz, strerror(errno));
            break;
        case 0:
            pid_t child2 = fork();
            switch (child2) {
            case -1:
                die("fork failed: %s\n".toStringz, strerror(errno));
                break;
            case 0:
                char* cwd = getcwd_by_pid(pid);
                if (cwd) {
                    res = chdir(cwd);
                    free(cwd);
                }
                execlp("st".toStringz, "./st".toStringz, null);
                break;
            default:
                exit(0);
            }
            break;
        default:
            wait(null);
            break;
        }
    }

    char* getcwd_by_pid(pid_t pid) {
        char[32] buf;
        snprintf(buf.ptr, buf.sizeof, "/proc/%d/cwd", pid);
        return realpath(buf.ptr, null);
    }
}