#!/usr/bin/env python3
"""默认预演；安装时只合并本组件，不启动容器或修改Cloudreve业务配置。"""
import argparse
import json
import os
from pathlib import Path
import pwd
import secrets
import shutil
import subprocess

SOURCE = Path(__file__).resolve().parent
BASE = Path('/opt/DockerDate/cloudreve-aria2')
TEMP = Path('/media/ztl/LinuxDate/cloudreve/offline-download')
GUARD = Path('/etc/usb-storage-guard.json')


def main():
    p = argparse.ArgumentParser()
    p.add_argument('--apply', action='store_true')
    a = p.parse_args()
    guard = json.loads(GUARD.read_text())
    disk = next(d for d in guard['disks'] if TEMP.is_relative_to(d['mountpoint']))
    mount = disk['mountpoint']
    found = subprocess.check_output(['findmnt', '-rn', '-M', mount, '-o', 'UUID,FSTYPE'], text=True).split()
    assert found == [disk['uuid'], disk['fstype']], '外盘身份不符，禁止创建目录'
    account = pwd.getpwnam('cloudreve')
    print('计划：部署Compose到', BASE)
    print('计划：共享临时目录', TEMP, '；UUID和文件系统已核对')
    for name in ('compose.yaml', 'Dockerfile'):
        dest = BASE / name
        if dest.exists():
            assert dest.read_bytes() == (SOURCE / name).read_bytes(), '已有部署内容不一致，拒绝覆盖：' + name
    assert not TEMP.is_symlink(), '拒绝符号链接目录'
    if not a.apply:
        print('预演完成：不写文件、不拉镜像、不启停服务、不修改节点。')
        return
    BASE.mkdir(parents=True, exist_ok=True, mode=0o755)
    TEMP.mkdir(exist_ok=True, mode=0o700)
    assert TEMP.stat().st_dev == Path(mount).stat().st_dev, '目录不在真实外盘'
    if TEMP.stat().st_uid != account.pw_uid:
        assert not any(TEMP.iterdir()), '已有数据目录属主不符，拒绝修改'
        os.chown(TEMP, account.pw_uid, account.pw_gid)
    for name in ('compose.yaml', 'Dockerfile'):
        dest = BASE / name
        if not dest.exists():
            shutil.copy2(SOURCE / name, dest)
    conf = BASE / 'aria2.conf'
    if not conf.exists():
        content = (SOURCE / 'aria2.conf.example').read_text().replace('__GENERATE_RANDOM_SECRET__', secrets.token_hex(32))
        fd = os.open(conf, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
        with os.fdopen(fd, 'w') as out:
            out.write(content)
        os.chown(conf, account.pw_uid, account.pw_gid)
    state = BASE / 'state'
    state.mkdir(exist_ok=True, mode=0o700)
    os.chown(state, account.pw_uid, account.pw_gid)
    session = state / 'session.txt'
    if not session.exists():
        session.touch(mode=0o600)
        os.chown(session, account.pw_uid, account.pw_gid)
    env = BASE / '.env'
    if not env.exists():
        env.write_text(f'CLOUDREVE_UID={account.pw_uid}\nCLOUDREVE_GID={account.pw_gid}\n')
        os.chmod(env, 0o644)
    print('文件就绪。请手工compose build/create，再运行manage.py configure --apply。')

if __name__ == '__main__':
    main()
