#!/bin/sh
# QueueDownload for dillo download.dpi 
# v0.2

# define the download location
dl_dir="$HOME/download"

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

url="$1"
filename=$dl_dir/$(basename "$url")

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

# read dpid comm port and shared secret
read prt secrt < $HOME/.dillo/dpid_comm_keys

# Hey dpid, what is downloads service/server port?
a=`nc 127.0.0.1 $prt << EOF
<dpi cmd='auth' msg='$secrt' '>
<dpi cmd='check_server' msg='downloads' '>
EOF
`

server_port=$(echo $a | cut -f4- -d"'" | rev | cut -c 5- | rev)

# Hi download.dpi, queue-download this!
nc 127.0.0.1 $server_port << EOF
<dpi cmd='auth' msg='$secrt' '>
<dpi cmd='download' url='$url' destination='$filename' '>
EOF
