#include <errno.h>
#include "genmap.h"
#include "shell.h"
#include "exceptions.h"
#include <std.h>

Root* Chdir(Root* arg)
{
    const StringC *string = Coerce2String(arg);
    char *new_dir = string->chars();
    if (string->leng() == 0) {
	new_dir = getenv("HOME");
	if (new_dir == NULL) new_dir = "";
    }
    if (chdir(new_dir) < 0)
	Signal(new BadSyscall("chdir \"%s\" failed", strdup(new_dir), errno));
    update_pwd(strdup(new_dir));
    return &NullSequence;
}

Root* DoRename(Root* old_name, Root* new_name)
{
    const StringC *old_string = Coerce2String(old_name);
    char *old_chars = old_string->chars();
    const StringC *new_string = Coerce2String(new_name);
    char *new_chars = new_string->chars();
    if (rename(old_chars, new_chars) < 0)
	Signal(new BadSyscall("rename \"%s\" \"%s\" failed",
			      old_chars, new_chars,
			      errno));
    return &NullSequence;
}

Root* DoExit(Root* code)
{
    const Integer *icode = ConvertInteger(code);
    if (icode == NULL) {
	cerr << "Q: " << *code << '\n';
	cerr.flush();
	exit(-1);
    }
    exit((char)(icode->S[0]));
}
