#!/bin/bash
# QueueDownload

if [ "$#" -ne 2 ]; then
   echo "Illegal number of parameters"  >&2
   echo "USAGE: $0 URL filename "
   exit 2
fi

url="$1"
filename="$2"

# start dpid?
if [ ! -f "$HOME/.dillo/dpid_comm_keys" ] ; then
   dpidc stop # to be sure
   dpid &
   sleep 2s
fi
read prt secrt < $HOME/.dillo/dpid_comm_keys

a=`nc 127.0.0.1 $prt << EOF
<dpi cmd='auth' msg='$secrt' '>
<dpi cmd='check_server' msg='downloads' '>
EOF
`
# expected dpip cmd: <cmd='send_data' msg='5034' '>
IFS="'" read -d '>' pre_cmd cmd msg_name server_port post <<< "$a"

if [ -z "$a" -o "$cmd" != "send_data" -o -z "$server_port" ] ; then 
   echo "ERROR: downloads server ¿not installed?"  >&2
   exit 1
fi

nc 127.0.0.1 $server_port << EOF
<dpi cmd='auth' msg='$secrt' '>
<dpi cmd='download' url='$url' destination='$filename' '>
EOF

