#!/bin/sh

[ -z "$(which grep)" ] && exit 0
[ -z "$(which awk)" ] && exit 0

echo "By default, dnscrypt-proxy will use the OpenDNS dnscrypt server."
echo "You may choose another one if you wish:"

SRVLIST=/opt/share/dnscrypt-proxy/dnscrypt-resolvers.csv
i=0
for serv in $(cat $SRVLIST | awk -F "," "{print \$1}")
do
    fullname=$(grep "^$serv," $SRVLIST | awk -F "," "{print \$2}" )
    if [ ! $i -eq 0 ]
    then
        echo "$i) $serv ($fullname)"
    fi
    i=`expr $i + 1`
done
read -p "Choose server from list or hit Enter to continue [1-`expr $i - 1`]: " OPTION
[ -z "$OPTION" ] && exit 0
srv=none
i=0
for serv in $(cat $SRVLIST | awk -F "," "{print \$1}")
do
    if [ ! $i -eq 0 ] && [ $i -eq $OPTION ]
    then
        srv=$serv
        break
    fi
    i=`expr $i + 1`
done
[ "$srv" == "none" ] && exit 0
SCRIPT=/opt/etc/init.d/S09dnscrypt-proxy
cat > $SCRIPT << EOF
#!/bin/sh

ENABLED=yes
PROCS=dnscrypt-proxy
ARGS="--local-address=127.0.0.1:65053 --daemonize -R $srv"
PREARGS=""
DESC=$PROCS
PATH=/opt/sbin:/opt/bin:/opt/usr/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

. /opt/etc/init.d/rc.func

EOF
chmod +x $SCRIPT
