292 lines
15 KiB
Python
292 lines
15 KiB
Python
#!/usr/bin/env python3
|
|
"""Prepare the tested Tekken 3 port and accessibility mod using local disc data."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path, PurePosixPath
|
|
import re
|
|
import shutil
|
|
import stat
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
from urllib.request import Request, urlopen
|
|
from zipfile import BadZipFile, ZipFile
|
|
|
|
|
|
PORT_COMMIT = "b6e941378ad03dbd834fef340bd8d90bae6e430b"
|
|
PORT_EXE_HASH = "25d038f55d7a1c02a0e5bbcc97fe9b1738c8292198e7fa0d1b171b57129d18c0"
|
|
SETUP_HASH = "c1e0430498b2f4212d7e04187e3ba822d3ac273de487cd35d93aa2ef823ac5aa"
|
|
RELEASE_API = "https://api.github.com/repos/BlindChallengerX/Tekken3-Access/releases/latest"
|
|
PRISM_HASH = "7c7d09c8c7306e8e1a0c46d603ccb2a391c194c77843400c11b746e7dd56a467"
|
|
USA_EXE_HASH = "fbda8b68e5799dbef4af39a161783bc670c15b0aa0e87dce65e210717da19b8c"
|
|
TRACK_SIZES = (632532768, 27701856, 28042896)
|
|
TRACK_NAMES = tuple(f"Tekken 3 (USA) (Track {trackNumber}).bin" for trackNumber in range(1, 4))
|
|
CUE_NAME = "Tekken 3 (USA).cue"
|
|
SECTOR_SIZE = 2352
|
|
|
|
|
|
def parse_release(releaseInfo):
|
|
if not isinstance(releaseInfo, dict) or releaseInfo.get("draft") is not False or releaseInfo.get("prerelease") is not False:
|
|
raise ValueError("GitHub did not return a published stable Tekken 3 Access release.")
|
|
versionMatch = re.fullmatch(r"v?(\d+(?:\.\d+)+)", str(releaseInfo.get("tag_name", "")))
|
|
if not versionMatch:
|
|
raise ValueError("The latest Tekken 3 Access release has an unsupported version tag.")
|
|
version = versionMatch.group(1)
|
|
archiveName = f"Tekken3Access-{version}.zip"
|
|
assets = releaseInfo.get("assets")
|
|
if not isinstance(assets, list):
|
|
raise ValueError("The latest release has no download assets.")
|
|
matchingAssets = [asset for asset in assets if isinstance(asset, dict) and asset.get("name") == archiveName]
|
|
if len(matchingAssets) != 1:
|
|
raise ValueError(f"The latest release must contain exactly one {archiveName} download.")
|
|
asset = matchingAssets[0]
|
|
downloadUrl = f"https://github.com/BlindChallengerX/Tekken3-Access/releases/download/{releaseInfo['tag_name']}/{archiveName}"
|
|
if asset.get("browser_download_url") != downloadUrl:
|
|
raise ValueError("The latest release has an unexpected download URL.")
|
|
digestMatch = re.fullmatch(r"sha256:([0-9a-f]{64})", str(asset.get("digest", "")))
|
|
if not digestMatch:
|
|
raise ValueError("GitHub did not supply a SHA-256 checksum for the latest release. Nothing was installed.")
|
|
return version, downloadUrl, digestMatch.group(1)
|
|
|
|
|
|
def latest_release():
|
|
request = Request(RELEASE_API, headers={"Accept": "application/vnd.github+json", "User-Agent": "audiogame-manager"})
|
|
with urlopen(request, timeout=30) as response:
|
|
return parse_release(json.load(response))
|
|
|
|
|
|
def validate_disc(discDir):
|
|
missingFiles = [name for name in (CUE_NAME, *TRACK_NAMES) if not (discDir / name).is_file()]
|
|
if missingFiles:
|
|
raise ValueError("Missing disc files in " + str(discDir) + ":\n" + "\n".join(missingFiles))
|
|
cueText = (discDir / CUE_NAME).read_text(encoding="utf-8-sig")
|
|
cueFiles = re.findall(r'^\s*FILE\s+"([^"]+)"\s+BINARY\s*$', cueText, re.MULTILINE | re.IGNORECASE)
|
|
cueTracks = re.findall(r"^\s*TRACK\s+(\d+)\s+(\S+)\s*$", cueText, re.MULTILINE | re.IGNORECASE)
|
|
if tuple(cueFiles) != TRACK_NAMES or [(int(number), mode.upper()) for number, mode in cueTracks] != [(1, "MODE2/2352"), (2, "AUDIO"), (3, "AUDIO")]:
|
|
raise ValueError("Expected a three-track Tekken 3 (USA) BIN/CUE dump with the listed filenames. Other layouts are not supported.")
|
|
for trackName, expectedSize in zip(TRACK_NAMES, TRACK_SIZES):
|
|
if (discDir / trackName).stat().st_size != expectedSize:
|
|
raise ValueError(f"{trackName} has an unexpected size. Check that the USA three-track dump is complete.")
|
|
with (discDir / TRACK_NAMES[0]).open("rb") as trackFile:
|
|
trackFile.seek(25 * SECTOR_SIZE)
|
|
rawExe = trackFile.read(579 * SECTOR_SIZE)
|
|
gameExe = b"".join(rawExe[offset + 24:offset + 24 + 2048] for offset in range(0, len(rawExe), SECTOR_SIZE))[:1185792]
|
|
if hashlib.sha256(gameExe).hexdigest() != USA_EXE_HASH:
|
|
raise ValueError("The disc executable does not match the tested Tekken 3 (USA) release. Check the region and integrity of the dump.")
|
|
|
|
|
|
def extract_archive(archivePath, destination, stripRoot=None):
|
|
"""Normalize Windows ZIP separators and reject paths outside the destination."""
|
|
with ZipFile(archivePath) as archive:
|
|
for member in archive.infolist():
|
|
name = member.filename.replace("\\", "/")
|
|
relativePath = PurePosixPath(name)
|
|
if relativePath.is_absolute() or ".." in relativePath.parts or ":" in name:
|
|
raise ValueError(f"Unsafe archive path: {member.filename}")
|
|
if stat.S_ISLNK(member.external_attr >> 16):
|
|
raise ValueError(f"Archive links are not supported: {member.filename}")
|
|
if stripRoot:
|
|
if not relativePath.parts or relativePath.parts[0] != stripRoot:
|
|
raise ValueError("The port archive has an unexpected top-level directory.")
|
|
relativePath = PurePosixPath(*relativePath.parts[1:])
|
|
if not relativePath.parts:
|
|
continue
|
|
outputPath = destination.joinpath(*relativePath.parts)
|
|
if member.is_dir() or name.endswith("/"):
|
|
outputPath.mkdir(parents=True, exist_ok=True)
|
|
else:
|
|
outputPath.parent.mkdir(parents=True, exist_ok=True)
|
|
with archive.open(member) as sourceFile, outputPath.open("wb") as outputFile:
|
|
shutil.copyfileobj(sourceFile, outputFile)
|
|
|
|
|
|
def verify_hash(path, expectedHash):
|
|
if hashlib.sha256(path.read_bytes()).hexdigest() != expectedHash:
|
|
raise ValueError(f"{path.name} does not match the expected checksum. Remove the cached download and retry.")
|
|
|
|
|
|
def validate_mod(gameRoot):
|
|
"""Accept the supported mod layout without replacing game data or user state."""
|
|
modFiles = {
|
|
"INSTALL.txt", "Play Tekken 3 Access.exe", "tekken 3 pc link.txt",
|
|
"Use controller.bat", "Use keyboard.bat", "T3Access/T3Access.dll",
|
|
"T3Access/prism.dll", "T3Access/README.txt", "T3Access/movies.txt",
|
|
}
|
|
for path in gameRoot.rglob("*"):
|
|
if not path.is_file():
|
|
continue
|
|
relativePath = path.relative_to(gameRoot)
|
|
if relativePath.as_posix() not in modFiles and not (relativePath.parent == Path("T3Access/ad") and relativePath.suffix == ".wav"):
|
|
raise ValueError(f"Unsupported release file: {relativePath}. Update its AGM integration before installing this release.")
|
|
for name in ("Play Tekken 3 Access.exe", "T3Access/T3Access.dll", "T3Access/README.txt"):
|
|
if not (gameRoot / name).is_file():
|
|
raise ValueError(f"The release is missing {name}.")
|
|
verify_hash(gameRoot / "T3Access/prism.dll", PRISM_HASH)
|
|
|
|
|
|
def write_manual(gameRoot):
|
|
manualText = (
|
|
"Tekken 3 Access under Wine\n\n"
|
|
"Keyboard: Enter starts; arrows move; Z/A/X/S are Square/Triangle/Cross/Circle.\n"
|
|
'Controller mode is enabled by default (p1_device = "auto"); connect your controller before launch.\n'
|
|
'To play with the keyboard, set p1_device = "keyboard" in settings.toml and restart.\n'
|
|
"The mod function keys work in either mode.\n"
|
|
"Alt+F4 exits. Settings, memory cards and logs are in this game folder.\n"
|
|
"AGM uses Prism's native Speech Dispatcher bridge for speech.\n"
|
|
"The upstream manual follows.\n\n"
|
|
)
|
|
(gameRoot / "manual.txt").write_text(manualText + (gameRoot / "T3Access/README.txt").read_text())
|
|
|
|
|
|
def check_game_stopped():
|
|
for processPath in Path("/proc").iterdir():
|
|
if not processPath.name.isdigit():
|
|
continue
|
|
try:
|
|
if processPath.stat().st_uid != os.getuid():
|
|
continue
|
|
arguments = (processPath / "cmdline").read_bytes().split(b"\0")
|
|
except (FileNotFoundError, ProcessLookupError, PermissionError):
|
|
continue
|
|
if any(argument.replace(b"\\", b"/").rsplit(b"/", 1)[-1].lower()
|
|
in (b"tekken3.exe", b"play tekken 3 access.exe") for argument in arguments):
|
|
raise ValueError("Close Tekken 3 and its access launcher before updating.")
|
|
|
|
|
|
def validate_installation(destination):
|
|
check_game_stopped()
|
|
if destination.is_symlink():
|
|
raise ValueError("The game directory must not be a symbolic link.")
|
|
verify_hash(destination / "Tekken3.exe", PORT_EXE_HASH)
|
|
for name in ("Play Tekken 3 Access.exe", "T3Access/T3Access.dll", "game_data/disc.cue", "settings.toml"):
|
|
if not (destination / name).is_file():
|
|
raise ValueError(f"The existing installation is missing {name}. Install Tekken 3 through AGM first.")
|
|
|
|
|
|
def update_game(modArchive, destination, modHash, modVersion):
|
|
validate_installation(destination)
|
|
verify_hash(modArchive, modHash)
|
|
with tempfile.TemporaryDirectory(prefix=".tekken3-update-", dir=destination.parent) as temporaryDir:
|
|
gameRoot = Path(temporaryDir) / "mod"
|
|
gameRoot.mkdir()
|
|
extract_archive(modArchive, gameRoot)
|
|
validate_mod(gameRoot)
|
|
write_manual(gameRoot)
|
|
relativeFiles = sorted(path.relative_to(gameRoot) for path in gameRoot.rglob("*") if path.is_file())
|
|
for relativePath in relativeFiles:
|
|
targetPath = destination / relativePath
|
|
for path in (targetPath, *targetPath.parents):
|
|
if path == destination.parent:
|
|
break
|
|
if path.is_symlink():
|
|
raise ValueError(f"Update target must not be a symbolic link: {path}")
|
|
if targetPath.exists() and not targetPath.is_file():
|
|
raise ValueError(f"Update target is not a file: {targetPath}")
|
|
for parentPath in targetPath.parents:
|
|
if parentPath == destination:
|
|
break
|
|
if parentPath.exists() and not parentPath.is_dir():
|
|
raise ValueError(f"Update target parent is not a directory: {parentPath}")
|
|
backupRoot = Path(tempfile.mkdtemp(prefix=".tekken3-access-backup-", dir=destination.parent))
|
|
for relativePath in relativeFiles:
|
|
sourcePath = destination / relativePath
|
|
if sourcePath.exists():
|
|
backupPath = backupRoot / relativePath
|
|
backupPath.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.copy2(sourcePath, backupPath)
|
|
check_game_stopped()
|
|
appliedFiles = []
|
|
try:
|
|
for relativePath in relativeFiles:
|
|
targetPath = destination / relativePath
|
|
targetPath.parent.mkdir(parents=True, exist_ok=True)
|
|
(gameRoot / relativePath).replace(targetPath)
|
|
appliedFiles.append(relativePath)
|
|
except OSError as error:
|
|
try:
|
|
for relativePath in reversed(appliedFiles):
|
|
targetPath = destination / relativePath
|
|
backupPath = backupRoot / relativePath
|
|
if backupPath.exists():
|
|
shutil.copy2(backupPath, targetPath)
|
|
else:
|
|
targetPath.unlink()
|
|
except OSError as restoreError:
|
|
raise OSError(f"Update and restoration failed. Restore files from {backupRoot}. {restoreError}") from error
|
|
raise OSError(f"Update failed; replaced files restored. Backup: {backupRoot}. {error}") from error
|
|
print(f"Updated Tekken 3 Access to {modVersion}. Backup of replaced files: {backupRoot}")
|
|
|
|
|
|
def install_game(discDir, portArchive, modArchive, destination, modHash, modVersion):
|
|
validate_disc(discDir)
|
|
verify_hash(modArchive, modHash)
|
|
if destination.exists() and any(destination.iterdir()):
|
|
raise ValueError(f"An installation already exists at {destination}. It was left untouched; back it up before reinstalling.")
|
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
with tempfile.TemporaryDirectory(prefix=".tekken3-setup-", dir=destination.parent) as temporaryDir:
|
|
gameRoot = Path(temporaryDir) / "game"
|
|
gameRoot.mkdir()
|
|
extract_archive(portArchive, gameRoot, f"Tekken3-PC-{PORT_COMMIT}")
|
|
verify_hash(gameRoot / "Tekken3.exe", PORT_EXE_HASH)
|
|
verify_hash(gameRoot / "setup_game_data.py", SETUP_HASH)
|
|
modRoot = Path(temporaryDir) / "mod"
|
|
modRoot.mkdir()
|
|
extract_archive(modArchive, modRoot)
|
|
validate_mod(modRoot)
|
|
shutil.copytree(modRoot, gameRoot, dirs_exist_ok=True)
|
|
subprocess.run([sys.executable, str(gameRoot / "setup_game_data.py"), str(discDir.resolve())], check=True)
|
|
for requiredFile in ("Play Tekken 3 Access.exe", "T3Access/T3Access.dll", "T3Access/prism.dll", "game_data/disc.cue"):
|
|
if not (gameRoot / requiredFile).is_file():
|
|
raise ValueError(f"Setup did not produce {requiredFile}.")
|
|
settingsPath = gameRoot / "settings.toml"
|
|
settingsText = settingsPath.read_text()
|
|
settingsPath.write_text(settingsText.replace("fullscreen = 1", "fullscreen = 0").replace("supersampling = 3", "supersampling = 1").replace("window_width = 1920", "window_width = 960").replace('p1_device = "keyboard"', 'p1_device = "auto"'))
|
|
write_manual(gameRoot)
|
|
if destination.exists():
|
|
destination.rmdir() # Only an empty destination is accepted above.
|
|
gameRoot.rename(destination)
|
|
print(f"Installed Tekken 3 Access {modVersion} in {destination}")
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
subparsers.add_parser("latest-release")
|
|
validateParser = subparsers.add_parser("validate-disc")
|
|
validateParser.add_argument("discDir", type=Path)
|
|
installedParser = subparsers.add_parser("validate-installation")
|
|
installedParser.add_argument("destination", type=Path)
|
|
updateParser = subparsers.add_parser("update")
|
|
updateParser.add_argument("modArchive", type=Path)
|
|
updateParser.add_argument("destination", type=Path)
|
|
installParser = subparsers.add_parser("install")
|
|
for name in ("discDir", "portArchive", "modArchive", "destination"):
|
|
installParser.add_argument(name, type=Path)
|
|
for commandParser in (updateParser, installParser):
|
|
commandParser.add_argument("--mod-sha256", required=True)
|
|
commandParser.add_argument("--mod-version", required=True)
|
|
args = parser.parse_args()
|
|
try:
|
|
if args.command == "latest-release":
|
|
print("\t".join(latest_release()))
|
|
elif args.command == "validate-disc":
|
|
validate_disc(args.discDir)
|
|
print("Tekken 3 (USA) disc files validated.")
|
|
elif args.command == "validate-installation":
|
|
validate_installation(args.destination)
|
|
elif args.command == "update":
|
|
update_game(args.modArchive, args.destination, args.mod_sha256, args.mod_version)
|
|
else:
|
|
install_game(args.discDir, args.portArchive, args.modArchive, args.destination, args.mod_sha256, args.mod_version)
|
|
except (OSError, ValueError, BadZipFile, subprocess.CalledProcessError) as error:
|
|
print(f"Tekken 3 setup failed: {error}", file=sys.stderr)
|
|
return 1
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|