#!/usr/bin/env python3
"""
BC-250 v3 amdgpu kernel module build script - Phase 1: Download & Prepare
"""
import paramiko
import sys

KERNEL_VER = "6.19.6"
KERNEL_FULL = "6.19.6-2-cachyos"
BUILD_DIR = "/home/fabian/kernel-build"
SRC_DIR = f"{BUILD_DIR}/linux-{KERNEL_VER}"

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.178.150', username='fabian', key_filename=r'C:\Users\fabia\.ssh\id_ed25519')

def run(cmd, desc="", timeout=600):
    if desc:
        print(f"\n=== {desc} ===")
    stdin, stdout, stderr = ssh.exec_command(cmd, timeout=timeout)
    out = stdout.read().decode().strip()
    err = stderr.read().decode().strip()
    rc = stdout.channel.recv_exit_status()
    if out:
        lines = out.split('\n')
        if len(lines) > 60:
            print('\n'.join(lines[:25]))
            print(f"  ... ({len(lines)-50} lines omitted) ...")
            print('\n'.join(lines[-25:]))
        else:
            print(out)
    if err and rc != 0:
        print(f"STDERR: {err[:500]}")
    if rc != 0:
        print(f"EXIT CODE: {rc}")
    return out, rc

# Step 1: Download kernel source if not present
out, rc = run(f"test -d {SRC_DIR} && echo EXISTS || echo MISSING")
if "EXISTS" in out:
    print(f"Kernel source already at {SRC_DIR}")
else:
    run(f"mkdir -p {BUILD_DIR}", "Creating build directory")
    run(f"cd {BUILD_DIR} && curl -LO https://cdn.kernel.org/pub/linux/kernel/v6.x/linux-{KERNEL_VER}.tar.xz",
        f"Downloading linux-{KERNEL_VER}.tar.xz", timeout=600)
    run(f"cd {BUILD_DIR} && tar xf linux-{KERNEL_VER}.tar.xz",
        "Extracting kernel source", timeout=300)
    run(f"rm -f {BUILD_DIR}/linux-{KERNEL_VER}.tar.xz")

# Step 2: Prepare build environment
run(f"cp /usr/lib/modules/{KERNEL_FULL}/build/.config {SRC_DIR}/", "Copying .config")
run(f"cp /usr/lib/modules/{KERNEL_FULL}/build/Module.symvers {SRC_DIR}/", "Copying Module.symvers")
run(f"cp /usr/lib/modules/{KERNEL_FULL}/build/localversion.10-pkgrel {SRC_DIR}/", "Copying localversion pkgrel")
run(f"cp /usr/lib/modules/{KERNEL_FULL}/build/localversion.20-pkgname {SRC_DIR}/", "Copying localversion pkgname")

run(f"cd {SRC_DIR} && make LLVM=1 olddefconfig 2>&1 | tail -5", "olddefconfig", timeout=120)
run(f"cd {SRC_DIR} && make LLVM=1 modules_prepare 2>&1 | tail -10", "modules_prepare", timeout=120)

# Verify
print("\n=== Source files ===")
AMDGPU = f"{SRC_DIR}/drivers/gpu/drm/amd/amdgpu"
for f in ["gfx_v10_0.c", "gmc_v10_0.c", "amdgpu_gmc.c"]:
    out, _ = run(f"wc -l {AMDGPU}/{f}")
    print(f"  {f}: {out.split()[0]} lines")

print("\n=== Phase 1 complete: source downloaded and prepared ===")
ssh.close()
