#!/bin/tcsh -f
#command line tool to list/insert/delete one-time calendar events

#caldav-synchronizable directory
set db="/home/jiri/mycalendar/1234abcd"
#your timezone
set TZNAME=Europe/Prague

setenv TZ $TZNAME
set now=`date +%s`"000"


#list all 
if ( ${#} == 0 ) then
vdirsyncer sync calendars  |& grep -v 'Syncing calendars'
rm -f /tmp/cal$$.tmp
foreach i ($db/*)
	printics $i >>  /tmp/cal$$.tmp
end
sort -n -k 1 </tmp/cal$$.tmp |awk '{printf("%-20s %-20s %3s %4s %2s %8s %4s %4s       %4s %20s\n",$2,$3,$4,$5,$6,$7,$8,$9,$10,$11);}'
rm /tmp/cal$$.tmp
exit 0
endif

if ( x"$1" == "xclean" || x"$1" == "xclear"  ) then
foreach i ($db/*)
        printics $i >>  /tmp/cal$$.tmp
end
set now=`date +%s`
set olds=`awk </tmp/cal$$.tmp '$1 < '$now'{print $NF}'`
rm  /tmp/cal$$.tmp
#echo rm $olds
foreach i ($olds)
rm $db/$i
end
vdirsyncer sync calendars  |& grep -v 'Syncing calendars'
exit 0
endif

set duration=3600
if ( x"$1" == "x-d"  ) then
	shift
	set duration=`expr $1 '*' 60`
	shift
endif

if ( x"$1" == "xadd"  ) then
shift
again:
set random=`exps -o 'random(-1);random(2^31-1)'`
set newfile=$db/$random.ics
if ( -e $newfile ) goto again
echo $random $* |calendar2ics >$newfile
set dateset=`grep DTSTART $newfile|awk -F: '{print $2}'`
if ( ${#dateset} != 1 ) then
echor -r Input error
rm -f $newfile
exit 1
endif

vdirsyncer sync calendars  |& grep -v 'Syncing calendars'
exit 0
endif

if ( x"$1" == "xdel"  ) then
shift
rm $db/$1
vdirsyncer sync calendars  |& grep -v 'Syncing calendars'
exit 0
endif

if ( x"$1" == "xedit"  ) then
shift
if ( ! -e $db/$1 ) then
echo file does not exist
exit 1
endif
if ( ${#EDITOR} == 0 ) EDITOR=vim
$EDITOR  $db/$1
vdirsyncer sync calendars  |& grep -v 'Syncing calendars'
exit 0
endif


if ( x"$1" == "xsync"  ) then
vdirsyncer sync calendars  |& grep -v 'Syncing calendars'
exit 0
endif


echo Unknown command $1
exit 1
