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

MANIFEST_PATH="${1:-$(dirname "$0")/MIROIR-PXE-DIRECT-DOWNLOADS-01-AVRIL-2026.txt}"
BASE_DIR="${2:-$PWD/mirror}"
DOWNLOADER="${DOWNLOADER:-wget}"

if [[ ! -f "$MANIFEST_PATH" ]]; then
  echo "Manifeste introuvable: $MANIFEST_PATH" >&2
  exit 1
fi

if ! command -v "$DOWNLOADER" >/dev/null 2>&1; then
  echo "Telechargeur introuvable: $DOWNLOADER" >&2
  echo "Installe wget ou lance avec DOWNLOADER=curl" >&2
  exit 1
fi

mkdir -p "$BASE_DIR"

download_with_wget() {
  local url="$1"
  local target="$2"
  wget -c -O "$target" "$url"
}

download_with_curl() {
  local url="$1"
  local target="$2"
  curl -L --fail --retry 3 --retry-delay 2 -o "$target" "$url"
}

line_no=0
while IFS='|' read -r relative_path url; do
  line_no=$((line_no + 1))

  if [[ -z "${relative_path}" ]]; then
    continue
  fi

  if [[ "${relative_path}" == \#* ]]; then
    continue
  fi

  if [[ -z "${url:-}" ]]; then
    echo "Ligne invalide ${line_no}: URL absente" >&2
    exit 1
  fi

  target="${BASE_DIR%/}/${relative_path}"
  target_dir="$(dirname "$target")"
  mkdir -p "$target_dir"

  echo "=== ${relative_path} ==="
  echo "URL    : ${url}"
  echo "CIBLE  : ${target}"

  if [[ "$DOWNLOADER" == "wget" ]]; then
    download_with_wget "$url" "$target"
  elif [[ "$DOWNLOADER" == "curl" ]]; then
    download_with_curl "$url" "$target"
  else
    echo "DOWNLOADER non supporte: $DOWNLOADER" >&2
    exit 1
  fi

  echo
done < "$MANIFEST_PATH"

echo "Telechargement termine dans: $BASE_DIR"
