#!/usr/bin/env bash
#
# calmerge - merge all events from multiple calendars into a single calendar
#
# ---
# source: https://github.com/cfenollosa/calmerge

# config
# set to 0 to blank all event names
allow_summary=1
# as many as you want (more than one) separated by spaces
in_urls="http://server.com/calendar1.ics http://server.com/calendar2.ics"
# output to a cloud folder to share it easily.
# use full paths (e.g. /home/user/cloud/out.ics)
out_file="out.ics"
# name that will be displayed in the client. leave blank to use first calendar's name
calname="out"

# code starts here
rm -f "${out_file}"

in_files=""
for url in ${in_urls}; do
  name=$(rndm).ics
  wget "${url}" -qO "${name}"
  in_files="${in_files} ${name}"
done

# allowed fields for events
allowed="DTEND DTSTAMP SEQUENCE DTSTART CREATED LAST-MODIFIED RRULE RECURRENCE-ID EXDATE"
[ "${allow_summary}" -eq 1 ] && allowed="${allowed} SUMMARY"

in_event=0
# inherit calendar metadata from first only
first_cal=1

# shellcheck disable=SC2022
for in_file in ${in_files}; do
  while read -r line; do
    echo "${line}" | grep -q 'BEGIN:VEVENT*' >/dev/null 2>&1 \
      && in_event=1 \
      && has_uid=0 \
      && echo "${line}" >>"${out_file}" && continue
    echo "${line}" | grep -q 'END:VEVENT*' >/dev/null 2>&1 \
      && in_event=0 echo "${line}" >>"${out_file}" && continue
    echo "${line}" | grep -q 'END:VCALENDAR*' >/dev/null 2>&1 && continue
    [ -n "${calname}" ] \
      && echo "${line}" | grep -q 'X-WR-CALNAME*' >/dev/null 2>&1 \
      && echo "X-WR-CALNAME:${calname}" >>"${out_file}" && continue

    if [ "${in_event}" -eq 1 ]; then
      for i in ${allowed}; do
        echo "${line}" | grep -q "${i}*" >/dev/null 2>&1 \
          && echo "${line}" >>"${out_file}" && continue
      done
      # use only event UID
      echo "${line}" | grep -q "UID:*" >/dev/null 2>&1 \
        && [ "${has_uid}" -eq 0 ] \
        && echo "${line}" >>"${out_file}" \
        && has_uid=1 && continue
      # only copy non-event data from first cal
    elif [ "${first_cal}" -eq 1 ]; then
      echo "${line}" >>"${out_file}" && continue
    fi
  done <"${in_file}"
  first_cal=0
done

echo "END:VCALENDAR" >>"${out_file}"

for file in ${in_files}; do
  rm "${file}"
done
