#!/bin/csh -f
#for android with kdeconnect

set phone=vpnpixel
set phoneid=57e8ec42_86a2_4aad_903d_5b6a4c750410


#find contact
set isnumber=`echo $1|awk '{if($1 ~ "^[+0-9][+0-9]*$") print 1; else print 0;}'`
if ($isnumber == 1) then
	set number=$1
else
	set number=`findcontact $1|awk '{print $1}'`
endif

if ( ${#number} != 1 ) then
exit 1
endif


set deviceok=`fping $phone |grep -c alive`
if ( $deviceok != 1 ) then
echo Phone not connected to VPN
exit 1
endif

kdeconnect-cli --refresh >& /dev/null
set available=`kdeconnect-cli -l |& grep 'paired'|grep $phoneid|wc -l`
if ( $available != 1 ) then
echo Phone not visible on kdeconnect
echo Unlock phone and retry
exit 1
endif

again:
set reachable=`kdeconnect-cli -l |& grep 'paired and reachable'|grep $phoneid|wc -l`
if ( $reachable != 1 ) then
echo Phone not reachable on kdeconnect
echo Unlock phone 
echo Retrying...
sleep 1
goto again
endif

echo Connection OK, go ahead



#read input
awk >/tmp/sms$$.tmp '{if($0==".") exit; else print $0;}'

#split to pieces
split -a 2 -b 160 /tmp/sms$$.tmp /tmp/sms$$.

#send
foreach i (/tmp/sms$$.??)
	set text=`cat $i`
	#echo SENDING MESSAGE $text to $number
	kdeconnect-cli -d $phoneid  --destination $number --send-sms "$text" >& /dev/null
end

rm -f /tmp/sms$$.*
