#!/usr/bin/env bash
########################################################################
# 2018-11-25 Lukas Bestle <project-shell@lukasbestle.com>
########################################################################
# Concats a directory of ICS files to a single ICS file for sharing
#
# Usage: radicale_to_ics <directory> <output.ics> [<calname>]
#
#        <directory>   Directory with ICS files (e.g. from Radicale)
#        <output.ics>  Output path for the concatenated ICS file
#        <calname>     Optional name of the ICS file
#                      (displayed in clients)
########################################################################

directory="$1"
output="$2"
calname="$3"

if [[ -z "$output" ]]; then
    # Print help
    echo -e "\033[1mUsage:\033[0m \033[34mradicale_to_ics\033[0m <directory> <output.ics> [<calname>]"
    exit 1
fi

# Place temporary file right next to the output file
# Will be moved when done with processing
tmp="$output.tmp"

# iCalendar header
echo "BEGIN:VCALENDAR" > "$tmp"
echo "VERSION:2.0" >> "$tmp"
echo "X-WR-TIMEZONE:Europe/Berlin" >> "$tmp"
echo "CALSCALE:GREGORIAN" >> "$tmp"
echo "METHOD:PUBLISH" >> "$tmp"

# Add calendar name if given
if [[ -n "$calname" ]]; then
    echo "X-WR-CALNAME:$calname" >> "$tmp"
fi

# Concat all event files in the given directory
# unless the directory is empty
if [[ "$(ls "$directory")" ]]; then
    for file in "$directory"/*; do
        # Extract all VEVENT elements (supports multiple per input file)
        sed '/^BEGIN:VEVENT/, /^END:VEVENT/!d' "$file" >> "$tmp"
    done
fi

# Add iCalendar footer
echo "END:VCALENDAR" >> "$tmp"

# Move to final destination
mv "$tmp" "$output"
