#!/bin/bash
set -Eeuo pipefail

# this script updates the README.md file with the content of the _dockerlists_*.md files
# inckluded in the ./update.sh 
# onyl run invidually if you need debugging or you want to update the README.md manually
echo " "
echo "# apply-readme.sh - update README.md with _dockerlists_*.md content"

for readme_group in debian alpine test; do
    echo "- check: _dockerlists_${readme_group}.md exists"
    # check exist .dockerlists_"${readme_group}".md
    if ! [ -f _dockerlists_"${readme_group}".md ]; then
      echo "File _dockerlists_${readme_group}.md not found!"
      echo "This file is required to update README.md"
      exit 1
    fi
done

# ------------- Update README.md ------------------
# Get current date and  Replace date in README.md
TODAY=$(date +%Y-%m-%d)
echo "- update VERSIONS date in README.md"
sed -i -r "s/(## Versions) \([0-9]{4}-[0-9]{2}-[0-9]{2}\)/\1 ($TODAY)/g" README.md
# Replace content between the special comments in README.md for each readme_group
for readme_group in debian alpine test; do
    echo "- update ${readme_group} table in README.md"
    awk -v readme_group="$readme_group" -v content="$(<_dockerlists_"${readme_group}".md)" '
    $0 ~ "<!-- "readme_group"_autogenerated_begin  -->" {print; print content; f=1; next}
    $0 ~ "<!-- "readme_group"_autogenerated_end  -->" {f=0}
    !f' README.md >tmp.md && mv tmp.md README.md
done

# Check README.md size; for safe uploading to the docker hub;
# https://github.com/peter-evans/dockerhub-description/issues/69
README_SIZE_LIMIT=25000
file_size=$(stat --format=%s "README.md")
echo " "
echo "README.md current size is $file_size bytes ( Docker Hub README.md max limit $README_SIZE_LIMIT bytes )"
if [[ $file_size -ge $README_SIZE_LIMIT ]]; then
    echo "WARNING: README.md is too large ($file_size bytes). "
    echo "  Must be less than $README_SIZE_LIMIT bytes!"
    echo "  The github API automatically truncates README.md files to $README_SIZE_LIMIT bytes."
    echo " "
fi

echo " "
echo "README.md updated successfully"
echo " "
