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

# Usage:
#   ./telecharger-windows-server-iso.sh ./WINDOWS-SERVER-ISO-OFFICIELS-02-AVRIL-2026.txt /opt/mirror
#
# Format manifeste:
#   relative_path|url

MANIFEST_PATH="${1:-}"
TARGET_ROOT="${2:-}"
DOWNLOADER="${DOWNLOADER:-wget}"
LOG_FILE="${LOG_FILE:-telechargement-windows-server-iso.log}"

if [[ -z "$MANIFEST_PATH" || -z "$TARGET_ROOT" ]]; then
  echo "Usage: $0 <manifest.txt> <target_root>"
  exit 1
fi

if [[ ! -f "$MANIFEST_PATH" ]]; then
  echo "Manifest introuvable: $MANIFEST_PATH"
  exit 1
fi

mkdir -p "$TARGET_ROOT"
touch "$LOG_FILE"

download_with_wget() {
  local url="$1"
  local out="$2"
  wget -c --tries=5 --timeout=30 --output-file="$LOG_FILE" -O "$out" "$url"
}

download_with_curl() {
  local url="$1"
  local out="$2"
  curl -L --fail --retry 5 --retry-delay 5 -C - -o "$out" "$url" >>"$LOG_FILE" 2>&1
}

line_no=0
while IFS= read -r raw_line || [[ -n "$raw_line" ]]; do
  line_no=$((line_no + 1))
  line="$(printf '%s' "$raw_line" | sed 's/\r$//')"

  [[ -z "$line" ]] && continue
  [[ "$line" =~ ^# ]] && continue

  rel_path="${line%%|*}"
  url="${line#*|}"

  if [[ -z "$rel_path" || -z "$url" || "$rel_path" == "$url" ]]; then
    echo "Ligne invalide $line_no: $line" | tee -a "$LOG_FILE"
    continue
  fi

  out_path="$TARGET_ROOT/$rel_path"
  out_dir="$(dirname "$out_path")"
  mkdir -p "$out_dir"

  echo "[$(date '+%F %T')] Download: $url" | tee -a "$LOG_FILE"
  echo "[$(date '+%F %T')] -> $out_path" | tee -a "$LOG_FILE"

  if [[ "$DOWNLOADER" == "curl" ]]; then
    download_with_curl "$url" "$out_path"
  else
    download_with_wget "$url" "$out_path"
  fi
done < "$MANIFEST_PATH"

echo "Termine. Log: $LOG_FILE"
