#!/usr/bin/env python3
"""
endless-download.py: download a file on a loop forever, rate capped, data discarded.

Nothing is written to disk. Live stats are redrawn in place every second (tmux-friendly).

Usage:
  ./endless-download.py                     # 410 Mbps, Leaseweb Sydney 10 GB test file
  ./endless-download.py -u ""               # auto-detect the current Ubuntu 24.04 ISO on AARNet
  ./endless-download.py -r 300              # different cap (Mbps)
  ./endless-download.py -u https://host/f   # custom URL
  ./endless-download.py -n 4                # 4 parallel streams sharing the cap

Ctrl+C stops it. Needs Python 3.8+, no extra packages.
"""

import argparse
import collections
import re
import sys
import threading
import time
import urllib.error
import urllib.request

DEFAULT_RATE_MBPS = 410
MIRROR_DIR = "https://mirror.aarnet.edu.au/pub/ubuntu/releases/24.04/"
CHUNK = 64 * 1024
UA = "Mozilla/5.0 (X11; Linux x86_64) endless-download/1.0"


# ---------- helpers ----------

def human_bytes(n):
    for unit, size in (("TB", 1e12), ("GB", 1e9), ("MB", 1e6), ("KB", 1e3)):
        if n >= size:
            return f"{n / size:.2f} {unit}"
    return f"{n:.0f} B"


def mbps(bytes_per_sec):
    return bytes_per_sec * 8 / 1e6


def hms(seconds):
    s = int(seconds)
    d, s = divmod(s, 86400)
    h, s = divmod(s, 3600)
    m, s = divmod(s, 60)
    return (f"{d}d " if d else "") + f"{h:02d}:{m:02d}:{s:02d}"


def request(url, method="GET"):
    return urllib.request.Request(url, method=method, headers={"User-Agent": UA})


def find_iso():
    """Old point releases get pulled from mirrors, so pick whatever is current."""
    with urllib.request.urlopen(request(MIRROR_DIR), timeout=15) as r:
        html = r.read().decode(errors="replace")
    isos = set(re.findall(r"ubuntu-24\.04(?:\.\d+)?-(?:desktop|live-server)-amd64\.iso", html))
    if not isos:
        return None

    def key(name):
        m = re.search(r"24\.04\.(\d+)", name)
        return (int(m.group(1)) if m else 0, "desktop" in name)  # newest first, prefer desktop (bigger)

    return MIRROR_DIR + max(isos, key=key)


# ---------- shared state ----------

class Limiter:
    """Token bucket shared by all streams, so the cap is total, not per stream."""

    def __init__(self, rate_bps):
        self.rate = rate_bps
        self.capacity = max(rate_bps * 0.25, CHUNK * 4)
        self.tokens = 0  # no burst at startup
        self.last = time.monotonic()
        self.lock = threading.Lock()

    def acquire(self, n):
        while True:
            with self.lock:
                now = time.monotonic()
                self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
                self.last = now
                if self.tokens >= n:
                    self.tokens -= n
                    return
                wait = (n - self.tokens) / self.rate
            time.sleep(wait)


class Stats:
    def __init__(self):
        self.lock = threading.Lock()
        self.total = 0
        self.passes = 0
        self.errors = 0
        self.last_event = "starting..."

    def add(self, n):
        with self.lock:
            self.total += n

    def event(self, msg, error=False, finished_pass=False):
        with self.lock:
            self.last_event = f"[{time.strftime('%H:%M:%S')}] {msg}"
            if error:
                self.errors += 1
            if finished_pass:
                self.passes += 1


# ---------- worker ----------

def worker(sid, url, limiter, stats, stop):
    n = 0
    while not stop.is_set():
        n += 1
        got = 0
        try:
            with urllib.request.urlopen(request(url), timeout=30) as r:
                while not stop.is_set():
                    limiter.acquire(CHUNK)
                    buf = r.read(CHUNK)
                    if not buf:
                        break
                    got += len(buf)
                    stats.add(len(buf))
            if not stop.is_set():
                stats.event(f"stream {sid} finished pass {n} ({human_bytes(got)})", finished_pass=True)
        except Exception as e:
            if stop.is_set():
                break
            stats.event(f"stream {sid} error: {e}, retrying in 5s", error=True)
            stop.wait(5)


# ---------- display ----------

def draw(lines, first):
    out = []
    if not first:
        out.append(f"\033[{len(lines)}F")  # cursor up to start of block
    for line in lines:
        out.append("\033[2K" + line + "\n")  # clear line, write
    sys.stdout.write("".join(out))
    sys.stdout.flush()


def main():
    ap = argparse.ArgumentParser(description="Endless rate-capped download (data discarded).")
    ap.add_argument("-r", "--rate", type=float, default=DEFAULT_RATE_MBPS, help="cap in Mbps")
    ap.add_argument("-u", "--url", default="http://speedtest.syd12.au.leaseweb.net/10000mb.bin", help="file to download")
    ap.add_argument("-n", "--streams", type=int, default=1, help="parallel streams")
    args = ap.parse_args()

    url = args.url
    if not url:
        try:
            url = find_iso()
        except Exception as e:
            sys.exit(f"Couldn't read {MIRROR_DIR}: {e}\nPass a file with -u <url>")
        if not url:
            sys.exit(f"No ISO found at {MIRROR_DIR}, pass a file with -u <url>")

    # Check once before looping
    try:
        with urllib.request.urlopen(request(url, "HEAD"), timeout=15) as r:
            size = int(r.headers.get("Content-Length") or 0)
    except urllib.error.HTTPError as e:
        sys.exit(f"URL returned HTTP {e.code}: {url}\nPick a different file with -u <url>")
    except Exception as e:
        sys.exit(f"Couldn't reach {url}: {e}")

    rate_bps = args.rate * 1e6 / 8
    limiter = Limiter(rate_bps)
    stats = Stats()
    stop = threading.Event()

    threads = [threading.Thread(target=worker, args=(i + 1, url, limiter, stats, stop), daemon=True)
               for i in range(args.streams)]
    for t in threads:
        t.start()

    start = time.monotonic()
    samples = collections.deque(maxlen=6)  # (time, total) for 5s average
    samples.append((start, 0))
    prev_t, prev_total = start, 0
    first = True

    print(f"URL:  {url}")
    print(f"File: {human_bytes(size) if size else 'unknown size'}   "
          f"Cap: {args.rate:g} Mbps across {args.streams} stream(s)   "
          f"(~{human_bytes(rate_bps * 3600)}/hour)   Ctrl+C to stop\n")

    try:
        while True:
            time.sleep(1)
            now = time.monotonic()
            with stats.lock:
                total, passes, errors, last = stats.total, stats.passes, stats.errors, stats.last_event
            samples.append((now, total))

            cur = (total - prev_total) / (now - prev_t)
            t0, b0 = samples[0]
            avg5 = (total - b0) / (now - t0) if now > t0 else 0
            elapsed = now - start
            overall = total / elapsed if elapsed else 0
            prev_t, prev_total = now, total

            pct = ""
            if size:
                pct = f"   (pass progress ~{(total % size) / size * 100:.0f}%)" if args.streams == 1 else ""

            draw([
                f"  Speed     {mbps(cur):7.1f} Mbps    5s avg {mbps(avg5):7.1f} Mbps",
                f"  Total     {human_bytes(total)}{pct}",
                f"  Elapsed   {hms(elapsed)}",
                f"  Average   {mbps(overall):7.1f} Mbps",
                f"  Passes    {passes}    Errors {errors}",
                f"  Last      {last}",
            ], first)
            first = False
    except KeyboardInterrupt:
        stop.set()
        elapsed = time.monotonic() - start
        with stats.lock:
            total = stats.total
        print(f"\nStopped after {hms(elapsed)}, {human_bytes(total)} downloaded "
              f"(avg {mbps(total / elapsed if elapsed else 0):.1f} Mbps)")


if __name__ == "__main__":
    main()
