#!/bin/bash

BASE_DIR="circuitx/master"
SOURCE="${BASE_DIR}/manifest.mpd"
TARGETS=("${BASE_DIR}/manifest4k.mpd" "${BASE_DIR}/manifest8k.mpd")

# Check source exists
if [ ! -f "$SOURCE" ]; then
  echo "ERROR: $SOURCE not found"
  exit 1
fi

# Extract values from source
AST=$(grep -oP 'availabilityStartTime="\K[^"]+' "$SOURCE")
PT=$(grep -oP 'publishTime="\K[^"]+' "$SOURCE")

if [ -z "$AST" ] || [ -z "$PT" ]; then
  echo "ERROR: Could not extract availabilityStartTime or publishTime from $SOURCE"
  exit 1
fi

echo "Source values:"
echo "  availabilityStartTime = $AST"
echo "  publishTime           = $PT"

# Replace in each target
for TARGET in "${TARGETS[@]}"; do
  if [ ! -f "$TARGET" ]; then
    echo "WARNING: $TARGET not found, skipping"
    continue
  fi

  sed -i \
    -e "s|availabilityStartTime=\"[^\"]*\"|availabilityStartTime=\"${AST}\"|g" \
    -e "s|publishTime=\"[^\"]*\"|publishTime=\"${PT}\"|g" \
    "$TARGET"

  echo "Updated: $TARGET"
done

echo "Done."
