#!/usr/bin/env bash
set -euo pipefail

# aria2c smart downloader for Apple InstallAssistant PKG
# Tries segmented downloads first, if server rejects -> retries with single-connection fallback + headers.
# Requires: aria2c in PATH.

declare -A FILES=(
  ["https://swcdn.apple.com/content/downloads/34/21/062-40406-A_GZQ27OUQER/ggclib72ow1omcvfexvp84bc9x5ei5tyqu/InstallAssistant.pkg"]="InstallAssistant_MacOS_Monterey_12.7.6.pkg"
  ["https://swcdn.apple.com/content/downloads/09/46/093-22004-A_QNZEDC334I/phigx2zvoggml6sh79my4y51fnvgy8hix4/InstallAssistant.pkg"]="InstallAssistant_MacOS_Ventura_13.7.8.pkg"
  ["https://swcdn.apple.com/content/downloads/35/20/093-53928-A_KHU5CMCSVU/a6n7xv7lgs90nra9g6swk8iv8qq5wp1ah3/InstallAssistant.pkg"]="InstallAssistant_MacOS_Sonoma_14.8.1.pkg"
  ["https://swcdn.apple.com/content/downloads/38/22/093-52107-A_OOVIFW6D5T/fze2nzd9lci8ook2pmu37mw39no53j6kyi/InstallAssistant.pkg"]="InstallAssistant_MacOS_Sequoia_15.7.1.pkg"
  ["https://swcdn.apple.com/content/downloads/27/44/093-50844-A_ADFZL6MD5J/3p92a0vzjzewywyitfwajte1w5t8t4pzts/InstallAssistant.pkg"]="InstallAssistant_MacOS_Tahoe_26.0.1.pkg"
)

# Global aria2 options (safe defaults)
COMMON_OPTS=(
  "--continue=true"            # resume
  "--max-tries=8"
  "--retry-wait=5"
  "--file-allocation=none"     # faster, less disk IO
  "--auto-file-renaming=false"
  "--allow-overwrite=true"
  "--summary-interval=0"       # reduce noise
)

# "fast" segmented attempt (may trigger invalid range on some CDNs)
FAST_OPTS=(
  "-c" "-x" "16" "-s" "16" "-j" "5" "-k" "1M"
)

# Headers to try if server requires them (user-agent + referer)
# You can adjust / remove if not needed.
UA="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6 Safari/605.1.15"
REFERER="https://swcdn.apple.com/"

LOGDIR="./aria2_logs"
mkdir -p "$LOGDIR"

failures=0

for url in "${!FILES[@]}"; do
  outfile="${FILES[$url]}"
  logfile="$LOGDIR/$(basename "$outfile").log"
  echo "----"
  echo "Starting: $outfile"
  echo "URL: $url"
  echo "Log: $logfile"
  echo

  # 1) Try fast segmented download
  echo "[*] Trying segmented download (fast mode) for $outfile..."
  aria2c "${COMMON_OPTS[@]}" "${FAST_OPTS[@]}" -o "$outfile" --log="$logfile" --log-level=notice "$url" || {
    ret=$?
    echo "[!] segmented attempt failed (exit $ret). Will retry with compatibility mode + headers."

    # 2) Retry with single-connection fallback + headers (compatible mode)
    echo "[*] Retrying with -x1 -s1 and headers..."
    aria2c "${COMMON_OPTS[@]}" -c -x 1 -s 1 -j 3 -o "$outfile" \
      --header="User-Agent: $UA" --header="Referer: $REFERER" \
      --log="$logfile" --log-level=notice "$url"

    ret2=$?
    if [ "$ret2" -ne 0 ]; then
      echo "[ERROR] Fallback also failed for $outfile (exit $ret2). See $logfile for details."
      failures=$((failures+1))
      continue
    fi
  }

  echo "[OK] Completed: $outfile"
done

echo "----"
if [ "$failures" -eq 0 ]; then
  echo "All downloads completed successfully."
else
  echo "Completed with $failures failure(s). Check $LOGDIR for logs."
fi
