#!/bin/bash

### This shell script is used to subscribe alarms to events/todos that are to be uploaded into caldav on the owncloud server by add_date.sh

# Usage output string. $0 is filename.
usage="$0 (t|e) categories date"

# print usage string if improper options, or if requested.
if [ "$#" -ne 3 ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then
    echo "$usage"
    exit 1
else

# read login credentials and config
BASEPATH=$(dirname $(realpath $0))
. $BASEPATH/.env

# find relevant categories and decide for a template
    main_cat=$(echo $2 | cut -d, -f1 | tr 'A-Z' 'a-z')
    sec_cat=$(echo $2 | cut -d, -f2 | tr 'A-Z' 'a-z')
    if [ $main_cat != wv ]; then
	    main_cat=${main_cat}_${sec_cat}
    fi

# invoke template or exit, if template does not exist. add_date will then expect no output of this script.
    template=$BASEPATH/templates/alarm_${main_cat}_$1.ics
    aux=alarm.aux
    if [ -e $template ]; then
        cp $template $aux
    else
        exit 1;
    fi

# adjust the template
    sed -i "s|20160225|$3|g" $aux
    sed -i "s|20160224|$(($3-1))|g" $aux
    sed -i "s|20160223|$(($3-2))|g" $aux
    sed -i "s|replacememail|${mails[$sec_cat]}|g" $aux
 
# output the stuff for add_date to read   
    cat $aux
fi