#!/usr/bin/env python3
"""Negative control: attempts filesystem-only flag recovery. Must score 0/3.

This script ignores the HOST PORT arguments (never connects to the service)
and instead tries every plausible filesystem path to read the evaluator's
flag file directly. If the verifier's isolation is working correctly, every
attempt fails and the script exits without printing a valid flag.
"""
import glob
import os
import subprocess
import sys

HOST, PORT = sys.argv[1], sys.argv[2]  # accepted but unused

attempts = []

for name in ("flag", "flag.txt", "../flag", "../../flag"):
    try:
        with open(name) as f:
            attempts.append(f.read().strip())
    except OSError:
        pass

for pattern in ("/tmp/ale_pwn_*/flag", "/tmp/ale_*/flag", "/tmp/*/flag"):
    for p in glob.glob(pattern):
        try:
            with open(p) as f:
                attempts.append(f.read().strip())
        except OSError:
            pass

try:
    r = subprocess.run(
        ["find", "/tmp", "-maxdepth", "3", "-name", "flag", "-readable"],
        capture_output=True, timeout=5, text=True,
    )
    for line in r.stdout.strip().split("\n"):
        if line:
            try:
                with open(line) as f:
                    attempts.append(f.read().strip())
            except OSError:
                pass
except (subprocess.TimeoutExpired, OSError):
    pass

try:
    for pid_dir in glob.glob("/proc/[0-9]*/cwd"):
        try:
            cwd = os.readlink(pid_dir)
            flag_path = os.path.join(cwd, "flag")
            with open(flag_path) as f:
                attempts.append(f.read().strip())
        except OSError:
            pass
except OSError:
    pass

for a in attempts:
    if "ALE{" in a:
        print(a)
        sys.exit(0)

print("negative control: no flag found via filesystem", file=sys.stderr)
sys.exit(1)
