#include "handler.ih"

void Handler::workingDir()
{
    size_t size = g_options.workingDir().length() + 1;
    if (not g_options.workingDirOption())           // -t not specified
        size += 6;

    char *cp = new char[size];
    cp[g_options.workingDir().copy(cp, string::npos)] = 0;

    unique_ptr<char []> mold{cp};

    if (not g_options.workingDirOption())
    {
        strcat(cp, "XXXXXX");
        if (mkdtemp(cp) == 0)         // 0 pointer returned on failure
            throw Exception{PANIC} << 
                            "can't create wotking dir `" << cp << '\'';

        g_options.workingDir(cp);
    }
    else 
    {
        error_code ec;
        if (not not create_directories(g_options.workingDir(), ec) and ec)
            throw Exception{PANIC} << "can't create working directory `" <<
                                       g_options.workingDir() << '\'';
    }

    if (chdir(g_options.workingDir().c_str()) != 0)
        throw Exception{PANIC} << "can't chdir to `" << 
                                            g_options.workingDir() << '\'';
}


