#!/bin/sh
# https://validator.w3.org/feed/
# https://validator.w3.org/feed/docs/atom.html#requiredFeedElements
# https://validator.w3.org/feed/docs/atom.html#requiredEntryElements

NAME="kevg"
STARTED_YEAR="2023"
TITLE="${NAME}'s thoughts"
WEBSITE="https://kevg.neocities.org/"
# https://www.ietf.org/rfc/rfc4151.txt
NAMESPACE="tag:${NAME},${STARTED_YEAR}:feed"
# For example, New York is UTC-4, so to get the afternoon of a day, add 4 hours
UTCAFTERNOON="17:00:00Z"

cat <<HEREDOC > feed.xml
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>${TITLE}</title>
  <link href="${WEBSITE}feed.xml" rel="self" />
  <link href="${WEBSITE}" />
  <id>${NAMESPACE}</id>
  <updated>$(date +%Y-%m-%dT%H:%M:%SZ)</updated>
  <author><name>${NAME}</name></author>

HEREDOC

awk -f- index.html <<HEREDOC >> feed.xml
insideEntry {
  if (\$0 ~ /<!-- End Blog Post/) {
    print "    ]]></content>";
    print "  </entry>";
    insideEntry = 0;
  } else {
    print;
  }
}

/<h2 id="thoughts/ {
  insideEntry = 1;

  id = \$0;
  gsub(/.*id="/, "", id);
  gsub(/".*/, "", id);
  
  title = \$0;
  gsub(/.*">/, "", title);
  gsub(/<\/h2.*/, "", title);
  gsub(/<\/?sup>/, "", title);
  
  year = title;
  gsub(/.*, /, "", year);
  
  month = "01";
  monthsearch = title;
  gsub(/ .*/, "", monthsearch);
  if (monthsearch ~ /Feb/) {
    month = "02";
  } else if (monthsearch ~ /Mar/) {
    month = "03";
  } else if (monthsearch ~ /Apr/) {
    month = "04";
  } else if (monthsearch ~ /May/) {
    month = "05";
  } else if (monthsearch ~ /Jun/) {
    month = "06";
  } else if (monthsearch ~ /Jul/) {
    month = "07";
  } else if (monthsearch ~ /Aug/) {
    month = "08";
  } else if (monthsearch ~ /Sep/) {
    month = "09";
  } else if (monthsearch ~ /Oct/) {
    month = "10";
  } else if (monthsearch ~ /Nov/) {
    month = "11";
  } else if (monthsearch ~ /Dec/) {
    month = "12";
  }
  
  day = title;
  gsub(/, .*/, "", day);
  gsub(/.* /, "", day);
  gsub(/th/, "", day);
  gsub(/st/, "", day);
  gsub(/nd/, "", day);
  if (length(day) == 1) {
    day = "0" day;
  }
  
  print "  <entry>";
  print "    <title>" title "</title>";
  print "    <link href=\"${WEBSITE}#" id "\" />";
  print "    <id>${NAMESPACE}entry#" id "</id>";
  print "    <published>" year "-" month "-" day "T${UTCAFTERNOON}</published>";
  print "    <updated>" year "-" month "-" day "T${UTCAFTERNOON}</updated>";
  print "    <content type=\"html\" xml:base=\"${WEBSITE}\"><![CDATA[";
}

/<!-- End Thoughts -->/ {
  exit 0;
}
HEREDOC

echo "</feed>" >> feed.xml
