# -*- coding: utf-8 -*-
"""只操作本程序创建的临时对象；全部数据为合成样本。"""
import os, sys, json, sqlite3, tempfile, pathlib, subprocess, time, socket, stat
from pathlib import Path
def emit(**kw):
    print(json.dumps(kw, ensure_ascii=False, sort_keys=True))
import shutil
with tempfile.TemporaryDirectory(prefix='ywebs-next132-b2-mount-') as d:
    p=Path(d); missing=p/'missing.yml'
    def preflight(q):
        if not q.is_file(): raise ValueError('挂载源必须是现存普通文件')
        return True
    try: preflight(missing); rejected=False
    except ValueError: rejected=True
    native=None; image=os.environ.get('DOCKER_LAB_IMAGE')
    if image:
        assert shutil.which('docker'); assert image=='postgres:16-alpine', '实验只允许已探测的本地固定镜像'
        mount='type=bind,src='+str(missing)+',dst=/tmp/demo.yml,readonly'
        r=subprocess.run(['docker','run','--rm','--network=none','--pull=never','--mount',mount,image,'true'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
        assert r.returncode!=0 and not missing.exists()
        v=p/'volume-missing.yml'
        q=subprocess.run(['docker','run','--rm','--network=none','--pull=never','-v',str(v)+':/tmp/demo.yml:ro',image,'true'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True)
        assert q.returncode==0 and v.is_dir()
        native={'mount_returncode':r.returncode,'mount_error':r.stderr,'volume_returncode':q.returncode,'volume_source_type':'directory'}
    good=p/'demo.yml'; good.write_text('demo: true'); assert preflight(good) and rejected
    emit(missing_rejected=rejected,good_file=True,docker=native)
