#!/usr/bin/env bash
set -e
OWNER="Matthias-Kaiser-35764"
REPO="Digitale-Bestellhilfe-3"
BRANCH="main"
ZIEL="/srv/apps/db3"
API="https://api.github.com/repos/$OWNER/$REPO/contents?ref=$BRANCH"

mkdir -p "$ZIEL"
echo "Hole Dateiliste von GitHub ..."
URLS=$(curl -s "$API" | grep -oE '"download_url":[[:space:]]*"[^"]*"' | sed -E 's/.*"download_url":[[:space:]]*"//; s/"$//')

if [ -z "$URLS" ]; then
  echo "FEHLER: keine Dateien gefunden. Repo-Name oder Branch pruefen."
  exit 1
fi

while IFS= read -r url; do
  [ -z "$url" ] && continue
  enc="${url##*/}"
  name=$(printf '%b' "${enc//%/\\x}")
  case "$name" in
    README.md) echo "  ueberspringe $name"; continue;;
  esac
  echo "  lade $name"
  curl -fsSL -o "$ZIEL/$name" "$url"
done <<< "$URLS"

if [ -f "$ZIEL/Digitale-Bestellhilfe.html" ]; then
  cp -f "$ZIEL/Digitale-Bestellhilfe.html" "$ZIEL/index.html"
  echo "index.html aus Digitale-Bestellhilfe.html erstellt."
fi

echo ""
echo "Fertig. Inhalt von $ZIEL:"
ls -la "$ZIEL"
