#!/usr/bin/env bash
#
# download_chunks.sh
#
# Reads manifest.json (a JSON object of { "name": "hash", ... }) and downloads
# each chunk from https://hl2.slqnt.dev/chunks/<name>.data using aria2c.
#
# Usage:
#   ./download_chunks.sh [manifest.json] [output_dir]
#
# Defaults:
#   manifest.json -> ./manifest.json
#   output_dir    -> ./chunks

set -euo pipefail

MANIFEST="${1:-manifest.json}"
OUTDIR="${2:-chunks}"
BASE_URL="https://hl2.slqnt.dev/chunks"
INPUT_FILE="aria2_input.txt"

if [ ! -f "$MANIFEST" ]; then
    echo "Error: manifest file '$MANIFEST' not found." >&2
    exit 1
fi

if ! command -v aria2c >/dev/null 2>&1; then
    echo "Error: aria2c is not installed. Install it with 'sudo apt install aria2' (or your package manager's equivalent)." >&2
    exit 1
fi

mkdir -p "$OUTDIR"

# Build the aria2c input file from the manifest's keys.
# Each entry gets:
#   <url>
#     out=<name>.data
python3 - "$MANIFEST" "$BASE_URL" "$INPUT_FILE" <<'PYEOF'
import json
import sys

manifest_path, base_url, input_path = sys.argv[1], sys.argv[2], sys.argv[3]

with open(manifest_path, "r") as f:
    manifest = json.load(f)

with open(input_path, "w") as out:
    for name in manifest.keys():
        out.write(f"{base_url}/{name}.data\n")
        out.write(f"  out={name}.data\n")

print(f"Wrote {len(manifest)} entries to {input_path}")
PYEOF

echo "Starting download with aria2c..."
aria2c \
    --input-file="$INPUT_FILE" \
    --dir="$OUTDIR" \
    --continue=true \
    --max-connection-per-server=16 \
    --split=1 \
    --max-concurrent-downloads=8 \
    --retry-wait=2 \
    --max-tries=5 \
    --auto-file-renaming=false \
    --allow-overwrite=true \
    --summary-interval=5

echo "Done. Files saved to '$OUTDIR/'."
