#!/bin/bash

BASE_URL="https://download.softwareschneiderei.de/lubw/fis-pegel/lung-staging"

LATEST_TXT_FILE="latest.txt"
echo "Lade ${LATEST_TXT_FILE} herunter"
curl -O "${BASE_URL}/${LATEST_TXT_FILE}"

while IFS= read -r line; do
  TAR_FILE_URL="${BASE_URL}/${line}"
  echo "Lade ${TAR_FILE_URL} herunter"
  curl -O "${TAR_FILE_URL}"
  TAR_FILENAME=$(basename "${TAR_FILE_URL}")
  SERVICE_NAME="${TAR_FILENAME%%-*}"
  echo "Registriere ${TAR_FILENAME} für Dienst ${SERVICE_NAME}"
  load_output=$(docker load -i "${TAR_FILENAME}")
  image_name=$(echo "$load_output" | grep -oP '(?<=Loaded image: ).*')
  echo "Geparster Image-Name: ${image_name}"
  docker tag "${image_name}" "marlin/${SERVICE_NAME}:latest"
  rm "${TAR_FILENAME}"
done < "${LATEST_TXT_FILE}"

rm "${LATEST_TXT_FILE}"

echo "Alle Docker-Images wurden heruntergeladen und in die lokale Docker-Registry gepusht"
