import shutil, configparser
from pathlib import Path

# 仓库在host上的地址
SHARED_ROOT = Path("/home/zhangyi/jupyter-collection")
CTRL_FILE   = SHARED_ROOT / ".hub" / "resource_map.ini"

def load_map():
    cfg = configparser.ConfigParser()
    cfg.read(CTRL_FILE)
    # 用户名 -> [res1, res2, ...]
    return {u: [r.strip() for r in v.split(",")]
            for u, v in cfg.items("users")}

def copy_resources(spawner):
    username = spawner.user.name
    shared   = Path(spawner.environment.get("HOME", f"/home/jupyter-{username}")) / "shared"

    # 清空或新建 shared
    if shared.exists():
        shutil.rmtree(shared)
    shared.mkdir(parents=True, exist_ok=True)

    # 按 ini 拷贝资源
    for res in load_map().get(username, []):
        src = SHARED_ROOT / res
        dst = shared / res
        if src.is_dir():
            shutil.copytree(src, dst, dirs_exist_ok=True)

# ========== 用户容器启动完成后执行 ==========
c.Spawner.post_spawn_hook = copy_resources