#!/bin/bash

URLBASE=http://103.3.189.125/davical/caldav.php
USR_ADMIN=hosting
PASSWORD_ADMIN=lot1KMch


# Exported files
if [ ! -d exported_calendars/ ]; then
        echo "Missing exported_calendars/"
        exit 1
fi

find exported_calendars/ -name *.ics | while read i; do
        # Format:
        # exported_calendars/user/name.ics
        USR=`echo "$i"|cut -f 2 -d '/'`
        CALENDAR_NAME=`echo "$i"|cut -f 3 -d '/'|sed 's_\.ics$__g'`

        # Default calendar is 'home' (change it here)
        # Other calendars (user:xxx) get translated into 'xxx'
        EXPSIMPLE=s/^${USR}\$/home/g
        CALENDAR_NAME=`echo "$CALENDAR_NAME"|sed "$EXPSIMPLE"|sed 's_^.*:\(.*\)$_\1_g'`

        echo DEBUG \[$i\] $USR, $CALENDAR_NAME >&2

        # Use cURL
        URL=${URLBASE}/${USR}/${CALENDAR_NAME}/
        curl --insecure --basic --request PUT --header \
                "Content-Type: text/calendar; charset=utf-8" \
                -u ${USR_ADMIN}:${PASSWORD_ADMIN} \
                --data-binary @${i} \
                $URL
        if [ $? -ne 0 ]; then
                echo ERROR with user $USR, calendar $CALENDAR_NAME >&2
        fi
done
