#!/bin/bash -e

# Ensure we are in a directory with debian/patches
if [ -d "debian/patches" ]; then
  find debian/patches -type f ! -name "series" | while read -r patch; do
    if ! grep -q "^Last-Update: " "$patch"; then
      if grep -q "^Date: " "$patch"; then
        sed -i 's/^Date: */Last-Update: /' $patch
      fi
    fi

    if grep -q "^Last-Update: " "$patch"; then
        original_line=$(grep "^Last-Update: " "$patch" | head -n 1)
        original_date=$(echo "$original_line" | cut -d' ' -f2-)

        # Try to parse the date. If it's already YYYY-MM-DD, skip it.
        # Check if the date command can handle the format.
        if [[ ! "$original_date" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
            # Use 'date' command to convert the string to ISO format
            new_date=$(date -d "$original_date" "+%Y-%m-%d" 2>/dev/null)
            if [ $? -eq 0 ]; then
                echo "Updating $patch: $original_date -> $new_date"
                # Using '|' as a delimiter in case the date contains '/'
                sed -i "s|^Last-Update: .*|Last-Update: $new_date|" "$patch"
            else
                echo "Warning: Could not parse date in $patch: '$original_date'"
            fi
        fi
    fi
  done
fi
