#!/usr/bin/env python3
"""ps4push — pull the PS4 files from the build host and drop them on the console.

Run this on any machine in the same network as the PS4. It downloads the
firmware image and the payload over HTTPS from the build host, then uploads them
to the console's FTP server (the one GoldHEN runs) at LAN speed.

    python ps4push.py 192.168.1.50
    python ps4push.py 192.168.1.50 --port 2121 --user anonymous --pass anonymous
    python ps4push.py --only image 192.168.1.50

Defaults match GoldHEN: port 2121, anonymous login.
"""
import argparse
import ftplib
import hashlib
import os
import sys
import time
import urllib.request

BASE = "https://ps4.hermescll.duckdns.org"

FILES = [
    {
        "name": "PS4PLATFORM.fd",
        "remote": "/data/ps4fw.fd",
        "sha256": "32a6ffb6d66a793e11529f34865c4f6604bc3a90c34003ea09ecda280fca0a34",
        "tag": "image",
    },
    {
        "name": "psw-agent.elf",
        "remote": "/data/payloads/psw-agent.elf",
        "sha256": "be1126ac6261e7a3f9f8d3b0845ec7edf34eba79c61fceef173ab21a1d99003d",
        "tag": "agent",
    },
]


def human(n):
    return f"{n / 1048576:.1f} MiB" if n >= 1048576 else f"{n / 1024:.0f} KiB"


def fetch(item, cache_dir="."):
    """Downloads the file next to this script and checks its hash."""
    path = os.path.join(cache_dir, item["name"])
    if os.path.exists(path):
        with open(path, "rb") as fh:
            if hashlib.sha256(fh.read()).hexdigest() == item["sha256"]:
                print(f"  {item['name']}: already here, hash ok")
                return path

    url = f"{BASE}/{item['name']}"
    print(f"  {item['name']}: downloading from {BASE}")
    started = time.time()
    with urllib.request.urlopen(url, timeout=60) as resp, open(path, "wb") as out:
        total = int(resp.headers.get("Content-Length") or 0)
        got = 0
        while True:
            chunk = resp.read(65536)
            if not chunk:
                break
            out.write(chunk)
            got += len(chunk)
            if total:
                pct = got * 100 // total
                sys.stdout.write(f"\r    {pct:3d}%  {human(got)} / {human(total)}")
                sys.stdout.flush()
    sys.stdout.write("\r    done" + " " * 30 + "\n")

    with open(path, "rb") as fh:
        digest = hashlib.sha256(fh.read()).hexdigest()
    if digest != item["sha256"]:
        print(f"  {item['name']}: HASH MISMATCH\n    got {digest}\n    want {item['sha256']}")
        return None
    print(f"  {item['name']}: hash ok ({human(os.path.getsize(path))}, {time.time() - started:.1f}s)")
    return path


def ensure_dir(ftp, remote_path):
    """Creates the parent directories of remote_path if FTP allows it."""
    parts = remote_path.strip("/").split("/")[:-1]
    cur = ""
    for part in parts:
        cur += "/" + part
        try:
            ftp.mkd(cur)
        except ftplib.error_perm:
            pass                      # already there, or not permitted


def upload(ftp, local_path, remote_path, label):
    size = os.path.getsize(local_path)
    ensure_dir(ftp, remote_path)
    print(f"  {label}: -> {remote_path} ({human(size)})")
    started = time.time()

    sent = 0

    def hook(chunk):
        # ftplib hands the callback the data, not a block number
        nonlocal sent
        sent += len(chunk)
        pct = min(100, sent * 100 // max(size, 1))
        sys.stdout.write(f"\r    {pct:3d}%  {human(min(sent, size))}")
        sys.stdout.flush()

    with open(local_path, "rb") as fh:
        ftp.storbinary(f"STOR {remote_path}", fh, blocksize=8192, callback=hook)
    elapsed = max(time.time() - started, 0.001)
    sys.stdout.write(f"\r    done  {human(size / elapsed)}/s" + " " * 20 + "\n")


def verify(ftp, remote_path, want_size):
    try:
        got = ftp.size(remote_path)
    except ftplib.all_errors:
        return True                   # server will not report size, trust the STOR
    if got != want_size:
        print(f"  {remote_path}: size on the console is {got}, expected {want_size}")
        return False
    print(f"  {remote_path}: {got} bytes on the console")
    return True


def main():
    ap = argparse.ArgumentParser(description="Push the PS4 firmware image and payload over FTP.")
    ap.add_argument("host", help="LAN address of the PS4, e.g. 192.168.1.50")
    ap.add_argument("--port", type=int, default=2121, help="FTP port (GoldHEN default 2121)")
    ap.add_argument("--user", default="anonymous")
    ap.add_argument("--password", default="anonymous")
    ap.add_argument("--only", choices=["image", "agent"], help="push just one file")
    ap.add_argument("--keep", action="store_true", help="keep the downloaded copies")
    args = ap.parse_args()

    items = [f for f in FILES if not args.only or f["tag"] == args.only]

    print(f"build host: {BASE}")
    local = []
    for item in items:
        path = fetch(item)
        if not path:
            return 1
        local.append((item, path))

    print(f"console   : {args.host}:{args.port} as {args.user}")
    ftp = ftplib.FTP()
    try:
        ftp.connect(args.host, args.port, timeout=20)
        ftp.login(args.user, args.password)
    except ftplib.all_errors as exc:
        print(f"  cannot connect: {exc}")
        print("  is the FTP server enabled in GoldHEN, and is this machine on the same network?")
        return 1

    ok = True
    try:
        ftp.voidcmd("TYPE I")
        for item, path in local:
            upload(ftp, path, item["remote"], item["name"])
            ok = verify(ftp, item["remote"], os.path.getsize(path)) and ok
    finally:
        try:
            ftp.quit()
        except ftplib.all_errors:
            ftp.close()

    if not args.keep:
        for _, path in local:
            try:
                os.remove(path)
            except OSError:
                pass

    print("PUSH: " + ("PASS" if ok else "FAIL"))
    if ok:
        print("tell the bench it is done and it will boot the image")
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())
