#!/usr/bin/env bash

PACKAGES_FILE="PACKAGES"

package=""
md5sum=""

# Print CSV header
echo "package,md5sum"

# Read the file line by line
while IFS= read -r line || [ -n "$line" ]; do
  # Check if line is empty (indicating end of a record)
  if [[ -z "$line" ]]; then
    # If both package and md5sum are set, print them in CSV format
    if [[ -n "$package" && -n "$md5sum" ]]; then
      echo "$package,$md5sum"
    fi
    # Reset variables for the next record
    package=""
    md5sum=""
  else
    # Extract the key and value
    key=$(echo "$line" | cut -d: -f1)
    value=$(echo "$line" | cut -d: -f2- | sed 's/^ //')

    # Assign values to package and md5sum variables
    if [[ "$key" == "Package" ]]; then
      package="$value"
    elif [[ "$key" == "MD5sum" ]]; then
      md5sum="$value"
    fi
  fi
done < "${PACKAGES_FILE}"

# Handle the last record if the file does not end with a blank line
if [[ -n "$package" && -n "$md5sum" ]]; then
  echo "$package,$md5sum"
fi
