#!/usr/bin/env python3
"""Test Redis container params on port 1000. Run, verify, then kill. No shell injection."""

import subprocess
import sys
import time

REDIS_IMAGE = "redis:latest"
CONTAINER_NAME = "redis_params_test_port1000"
TEST_PASSWORD = 'p@ss!word#$%^&*() spaces_and-special'  # Deliberately nasty
HOST_PORT = 1000
CONTAINER_PORT = 6379

# Same args as action_instance.redis_setup_execute (subprocess list, no shell)
redis_cmd = [
    "docker", "run", "-d",
    "-p", f"{HOST_PORT}:{CONTAINER_PORT}",
    "--name", CONTAINER_NAME,
    REDIS_IMAGE,
    "redis-server",
    "--bind", "0.0.0.0",
    "--requirepass", TEST_PASSWORD,
    "--save", "",
    "--appendonly", "no",
    "--activerehashing", "yes",
    "--tcp-keepalive", "300",
    "--tcp-backlog", "511",
    "--maxclients", "10000",
    "--maxmemory-policy", "allkeys-lru",
]


def main():
    print("Cleaning up any leftover container...")
    subprocess.run(["docker", "rm", "-f", CONTAINER_NAME], capture_output=True)

    print(f"\nStarting Redis on port {HOST_PORT} with password containing special chars...")
    proc = subprocess.run(redis_cmd, capture_output=True, text=True, timeout=30)
    if proc.returncode != 0:
        print("FAILED to start Redis:", proc.stderr or proc.stdout)
        sys.exit(1)

    print("Waiting for Redis to be ready...")
    time.sleep(3)

    # Test with redis-cli (AUTH + PING)
    auth_cmd = ["redis-cli", "-p", str(HOST_PORT), "-a", TEST_PASSWORD, "PING"]
    ping = subprocess.run(auth_cmd, capture_output=True, text=True, timeout=5)
    if ping.returncode != 0 or "PONG" not in (ping.stdout or "").upper():
        print("FAILED: Redis did not respond to PING:", ping.stdout, ping.stderr)
        subprocess.run(["docker", "rm", "-f", CONTAINER_NAME], capture_output=True)
        sys.exit(1)

    print("OK: Redis PING succeeded with special-char password")

    # Quick SET/GET
    set_cmd = ["redis-cli", "-p", str(HOST_PORT), "-a", TEST_PASSWORD, "SET", "test", "ok"]
    subprocess.run(set_cmd, capture_output=True, timeout=5)
    get_cmd = ["redis-cli", "-p", str(HOST_PORT), "-a", TEST_PASSWORD, "GET", "test"]
    get_proc = subprocess.run(get_cmd, capture_output=True, text=True, timeout=5)
    if "ok" not in (get_proc.stdout or ""):
        print("FAILED: SET/GET check:", get_proc.stdout, get_proc.stderr)
    else:
        print("OK: SET/GET works")

    print("\nKilling and removing container...")
    subprocess.run(["docker", "rm", "-f", CONTAINER_NAME], check=True)
    print("Done. Params are OK.")


if __name__ == "__main__":
    main()
