#include <lib.h>


int flag[256];

int mkdir(char* path) {
	struct Stat st;
	int r = stat(path, &st);
	if (r >= 0) {
		if (flag['p']) {
			return 0;
		} else {
			printf("mkdir: cannot create directory '%s': File exists\n", path);
			return 1;
		}
	}
	if (flag['p']) {
    char cur_path[MAXPATHLEN];
    syscall_get_env_dir(0, cur_path);  // 获取当前目录

    char full_path[MAXPATHLEN];
    merge_path(full_path, cur_path, path);  // 构建完整路径

    // 定位最后一个目录分隔符
    char *last_slash = strrchr(full_path, '/');
    
    // 处理根目录特殊情况
    if (last_slash == full_path) {
        last_slash++;  // 根目录保持为"/"
    }
    
    // 截断路径获取父目录
    char parent_path[MAXPATHLEN];
    if (last_slash) {
        size_t parent_len = last_slash - full_path;
        strncpy(parent_path, full_path, parent_len);
        parent_path[parent_len] = '\0';
    } else {
        strcpy(parent_path, ".");  // 无分隔符时使用当前目录
    }

    // 检查并创建父目录
    int r = stat(parent_path, &st);
    if (r == -E_NOT_FOUND) {
        if ((r = mkdir(parent_path)) < 0) {
            return r;
        }
    } else if (r < 0) {
        return r;
    }
}

	r = create(path, 1);
	if (r == -E_NOT_FOUND) {
		printf("mkdir: cannot create directory '%s': No such file or directory\n", path);
		return 1;
	} else {
		return 0;
	}
}

void usage() {
	printf("usage: mkdir [-p] <file>\n");
	exit(1);
}

int main(int argc, char **argv) {
	ARGBEGIN {
	default:
		usage();
	case 'p':
		flag[(u_char)ARGC()]++;
		break;
	}
	ARGEND
	if (argc != 1) {
		usage();
	}
	int ret = mkdir(argv[0]);
	return ret;
}
