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

# Downloads the WinIBW Standard-Scripts bundles and replaces existing files if present.
# - Main: v3.1/allFiles.zip to the specified output path
# - German: v3.1/German/allFiles.zip to a 'German' subfolder next to the output path
#
# Usage:
#   ./download_allFiles.sh [output_path]
# If output_path is omitted, defaults to ./allFiles.zip

URL_MAIN="https://cbs-nl.oclc.org/htdocs/winibw/Standard-Scripts/v3.1/allFiles.zip"
URL_DE="https://cbs-nl.oclc.org/htdocs/winibw/Standard-Scripts/v3.1/German/allFiles.zip"

out="${1:-allFiles.zip}"

# Use a temp file next to the destination to avoid partial files being visible
out_dir="$(dirname "$out")"
mkdir -p "$out_dir"

# Prepare German output path under subfolder 'German'
german_dir="${out_dir}/German"
mkdir -p "$german_dir"
german_out="${german_dir}/allFiles.zip"

# Simple portable temp names (avoid mktemp quirks on Windows Git Bash)
tmp_main="${out}.download.$$"
tmp_de="${german_out}.download.$$"

cleanup() {
  rm -f "${tmp_main:-}" 2>/dev/null || true
  rm -f "${tmp_de:-}" 2>/dev/null || true
}
trap cleanup EXIT

# Download MAIN using curl or wget
if command -v curl >/dev/null 2>&1; then
  curl -fL --retry 3 --retry-connrefused --connect-timeout 10 "$URL_MAIN" -o "$tmp_main"
elif command -v wget >/dev/null 2>&1; then
  wget -q --tries=3 --timeout=20 -O "$tmp_main" "$URL_MAIN"
else
  echo "Error: curl or wget is required to download files." >&2
  exit 1
fi

# Atomically replace MAIN destination
mv -f "$tmp_main" "$out"
echo "Downloaded main: $out"

# Download GERMAN using curl or wget
if command -v curl >/dev/null 2>&1; then
  curl -fL --retry 3 --retry-connrefused --connect-timeout 10 "$URL_DE" -o "$tmp_de"
elif command -v wget >/dev/null 2>&1; then
  wget -q --tries=3 --timeout=20 -O "$tmp_de" "$URL_DE"
else
  echo "Error: curl or wget is required to download files." >&2
  exit 1
fi

# Atomically replace GERMAN destination
mv -f "$tmp_de" "$german_out"
echo "Downloaded German: $german_out"