#!/usr/bin/env python3
"""Test script for skopeo experimental-image-proxy"""

import socket
import subprocess
import json
import sys
import os

def main():
    # Create a SOCK_SEQPACKET socketpair
    parent_sock, child_sock = socket.socketpair(socket.AF_UNIX, socket.SOCK_SEQPACKET)

    print("Starting skopeo experimental-image-proxy...", file=sys.stderr)

    # Start skopeo with strace
    strace_log = "/tmp/skopeo-strace.log"
    stderr_log = "/tmp/skopeo-stderr.log"

    with open(stderr_log, 'w') as stderr_f:
        proc = subprocess.Popen(
            ["strace", "-f", "-o", strace_log,
             "skopeo", "experimental-image-proxy", "--debug"],
            stdin=child_sock.fileno(),
            stdout=stderr_f,
            stderr=stderr_f,
            pass_fds=(child_sock.fileno(),)
        )

    # Close child socket in parent
    child_sock.close()

    # Send Initialize request
    print("Sending Initialize request...", file=sys.stderr)
    request = {"method": "Initialize", "args": []}
    parent_sock.send(json.dumps(request).encode())

    # Try to receive response
    try:
        response_data = parent_sock.recv(4096)
        if response_data:
            response = json.loads(response_data)
            print(f"Initialize Response: {json.dumps(response, indent=2)}", file=sys.stderr)
        else:
            print("No response received", file=sys.stderr)
    except Exception as e:
        print(f"Error receiving response: {e}", file=sys.stderr)

    # Send Shutdown request
    print("Sending Shutdown request...", file=sys.stderr)
    shutdown_request = {"method": "Shutdown", "args": []}
    parent_sock.send(json.dumps(shutdown_request).encode())

    # Try to receive shutdown response
    try:
        response_data = parent_sock.recv(4096)
        if response_data:
            response = json.loads(response_data)
            print(f"Shutdown Response: {json.dumps(response, indent=2)}", file=sys.stderr)
    except Exception as e:
        print(f"Error receiving shutdown response: {e}", file=sys.stderr)

    # Wait for process to exit
    proc.wait(timeout=5)
    print(f"Process exited with code: {proc.returncode}", file=sys.stderr)

    # Show stderr
    print("\n=== STDERR ===", file=sys.stderr)
    with open(stderr_log) as f:
        print(f.read(), file=sys.stderr)

    # Show filtered strace
    print("\n=== STRACE (filtered for podman/unshare/exec) ===", file=sys.stderr)
    try:
        result = subprocess.run(
            ["grep", "-E", "podman|unshare|execve", strace_log],
            capture_output=True,
            text=True
        )
        if result.stdout:
            print(result.stdout, file=sys.stderr)
        else:
            print("No podman/unshare/exec calls found", file=sys.stderr)
    except Exception as e:
        print(f"Error reading strace: {e}", file=sys.stderr)

    parent_sock.close()

    # Cleanup
    try:
        os.unlink(strace_log)
        os.unlink(stderr_log)
    except:
        pass

if __name__ == "__main__":
    main()
