#!/bin/tcsh -f
#command line tool to list/insert/delete/search contacts

#carddav-synchronizable directory
set db="/home/jiri/mycontacts/abcd1234"


#list all 
if ( ${#} == 0 ) then
vdirsyncer sync contacts  |& grep -v 'Syncing contacts'
rm -f /tmp/con$$.tmp
foreach i ($db/*)
	printvcf $i >>  /tmp/con$$.tmp
end
sort -k 1 </tmp/con$$.tmp
rm /tmp/con$$.tmp
exit 0
endif

if ( x"$1" == "xadd"  ) then
shift

if ( ${#} != 2 ) then
echo missing name or number
exit 1
endif

set results=`findcontact -n $1|awk '{print $1}'`
if( ${#results} > 0 ) then
echo name already exists
exit 1
endif

again:
set random=`od -x /dev/random|head -1|awk '{printf("%4s%4s-%4s-%4s-%4s-%4s%4s%4s",$2,$3,$4,$5,$6,$7,$8,$9);}'`
set newfile=$db/$random.vcf
if ( -e $newfile ) goto again
echo $random $* |contact2vcf >$newfile
vdirsyncer sync contacts  |& grep -v 'Syncing contacts'
exit 0
endif


if ( x"$1" == "xdel"  ) then
shift
if ( ${#} == 0 ) then
echo missing name
exit 1
endif
set file=`findcontact $1|awk '{print $2}'`
if ( ${#file} == 0 ) then
exit 1
endif
if ( ! -e $file ) then
echo internal error in contacts
exit 1
endif
rm $file
vdirsyncer sync contacts  |& grep -v 'Syncing contacts'
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 contacts  |& grep -v 'Syncing contacts'
exit 0
endif


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


#find a particular contact or number
#vdirsyncer sync contacts  |& grep -v 'Syncing contacts'
set isnumber=`echo $1|awk '{if($1 ~ "^[+0-9][+0-9]*$") print 1; else print 0;}'`
if ($isnumber == 1) then
	set results=`findreversecontact $1`
	if( ${#results} != 2 ) then
		echor -r try contacts sync
                exit 1
        endif
        set searched=`grep '^TEL.*:' $results[2]|awk -F: '{print $2}'`
else
        set results=`findcontact $1`
	if( ${#results} != 2 ) then
		echor -r try contacts sync
		exit 1
	endif
	set searched=`grep '^N:.*;;;' $results[2]|awk -F: '{print $2}'|tr ';' ' '`
endif

echo $searched ' ' $results[1] '      FILE  ' `basename $results[2]`
