#!/bin/bash

ICS_URL="$1"

if [ -z "$ICS_URL" ]; then
  echo "Usage: $0 <ICS_URL>"
  exit 1
fi

ICS_DATA=$(curl -s "$ICS_URL")

TODAY=$(date +%Y%m%d)

echo "_model: page"
echo "---"
echo "title: Termine"
echo "---"
echo "body:"
echo ""
echo "| **Datum** | **Anlass** | **Zeit** | **Ort** |"
echo "|-------|--------|------|-----|"

#original statement:
#awk 'BEGIN{FS=":"}/^DTSTART/{dtstart=$2}/^SUMMARY/{summary=$2}/^END:VEVENT/{print substr(dtstart,7,2)"/"substr(dtstart,5,2)"/"substr(dtstart,1,4),sprintf("%02d",substr(dtstart,10,2)+3)":"substr(dtstart,12,2),summary}' file.txt
#from here: https://stackoverflow.com/questions/74111401/parse-ics-and-create-output

echo "$ICS_DATA" | awk 'BEGIN{FS=":"}
/^DTSTART/{dtstart=$2}
/^SUMMARY/{summary=$2}
/^LOCATION/{location=$2}
/^END:VEVENT/{
  gsub(/\r/, "", summary)
  gsub(/\r/, "", location)
  if (dtstart == "") dtstart = "19700101T000000"
  if (summary == "") summary = " "
  if (location == "") location = " "

  date_str = substr(dtstart, 1, 4) "-" substr(dtstart, 5, 2) "-" substr(dtstart, 7, 2)
  cmd = "LC_ALL=de_DE.UTF-8 date -d \"" date_str "\" +%a"
  cmd | getline weekday
  close(cmd)

  cmd = "LC_ALL=de_DE.UTF-8 date -d \"" date_str "\" +%B"
  cmd | getline month
  close(cmd)

  orderstartdate=sprintf("%s", substr(dtstart,1,8))
  realstartdate=sprintf("%s. %d. %s %s", weekday, substr(dtstart,7,2), month, substr(dtstart, 1, 4))
  starttime=sprintf("%02d:%02d", substr(dtstart,10,2), substr(dtstart,12,2))
  summarystring=sprintf("%s", summary)
  locationstring=sprintf("%s", location)
  wholeline=sprintf("%s | %s | %s | %s | %s |", orderstartdate, realstartdate, summarystring, starttime, location)
  gsub(/\| 00:00 \|/, "| |", wholeline)
  print wholeline
  dtstart=""
  summary=""
  location=""
}' | awk -v today="$TODAY" 'substr($1,1,8) >= today' | sort | awk '{$1=""}1' | awk '{$1=$1}1'

echo ""
