#!/usr/bin/env python3
"""Compile/test the existing AES C reference with isolated GCC and CMake builds."""
import os
import shutil
import subprocess
import tempfile
from pathlib import Path

SRC=Path(__file__).resolve().parent
EXPECTED=("3925841d02dc09fbdc118597196a0b32","AES-128 known answer and inverse PASS")
def run(*args,cwd=None):
    p=subprocess.run(args,cwd=cwd,check=True,capture_output=True,text=True)
    return p.stdout.strip()
def main():
    for cmd in ("gcc","make","cmake"):
        if shutil.which(cmd) is None:
            raise RuntimeError("Missing native tool: "+cmd)
    with tempfile.TemporaryDirectory(prefix="aes-spectral-") as tmp:
        d=Path(tmp)
        for name in ("aes.c","Makefile","CMakeLists.txt"):
            shutil.copy2(SRC/name,d/name)
        run("make","test",cwd=d)
        assert run(str(d/"aes_encryptor"),cwd=d).splitlines()==list(EXPECTED)
        run("make","clean",cwd=d)
        run("cmake","-S",str(d),"-B",str(d/"build"),cwd=d)
        run("cmake","--build",str(d/"build"),cwd=d)
        run("ctest","--test-dir",str(d/"build"),"--output-on-failure",cwd=d)
        assert run(str(d/"build"/"aes_encryptor"),cwd=d).splitlines()==list(EXPECTED)
    print("GCC strict C99: PASS; Makefile: PASS; CMake/CTest: PASS; AES-128 known-answer and inverse: PASS")
if __name__=="__main__":main()
