#!/usr/bin/env python3
"""Fake `docker` for the hermetic tests. Records every invocation to $FAKE_DOCKER_LOG (one JSON
line per call) and answers from $FAKE_DOCKER_STATE (a JSON file the test writes):

    {"ps": [{"Name": "see", "State": "running", "Health": "healthy"}],   # compose ps output
     "fail": ["pull"],          # sub-commands that must exit 1
     "free_root": "/tmp"}       # DockerRootDir for `docker info`
"""

import json
import os
import sys


def main() -> int:
    argv = sys.argv[1:]
    state = {}
    sp = os.environ.get("FAKE_DOCKER_STATE")
    if sp and os.path.exists(sp):
        with open(sp) as fh:
            state = json.load(fh)
    lp = os.environ.get("FAKE_DOCKER_LOG")
    if lp:
        with open(lp, "a") as fh:
            fh.write(json.dumps({"argv": argv, "cwd": os.getcwd()}) + "\n")
    fail = set(state.get("fail", []))
    if argv[:1] == ["version"]:
        print("28.3.0")
        return 0
    if argv[:1] == ["info"]:
        print(state.get("free_root", "/"))
        return 0
    if argv[:2] == ["image", "prune"]:
        return 0
    if argv[:1] == ["compose"]:
        # strip global compose flags
        rest = argv[1:]
        while rest and rest[0].startswith("--"):
            rest = rest[2:]
        sub = rest[0] if rest else ""
        if sub == "version":
            print("2.32.0")
            return 0
        if sub in fail:
            print(f"fake docker: {sub} failed", file=sys.stderr)
            return 1
        if sub == "ps":
            for row in state.get("ps", []):
                print(json.dumps(row))
            return 0
        if sub == "logs":
            print("fake compose logs")
            return 0
        if sub == "up" and state.get("env_file_check"):
            # prove the .env is complete and 0600
            d = os.getcwd()
            env = os.path.join(d, ".env")
            st = os.stat(env)
            if st.st_mode & 0o077:
                print("fake docker: .env is not 0600", file=sys.stderr)
                return 1
        return 0
    print(f"fake docker: unknown {argv}", file=sys.stderr)
    return 2


if __name__ == "__main__":
    sys.exit(main())
